Search code examples
phpsymfonyclassnotfoundexceptionfatal-error

PHP Symfony- How to inherit multiple classes from one php file


I am using Symfony 2.4

I have a PHP file OAuth.php which has multiple classes inside that.

Code of OAuth.php is as below

<?php

namespace RT\AuthBundle\DependencyInjection\Vzaar;
use Exception;

class OAuthException extends Exception {
  // pass
}

class OAuthConsumer {
     //some code
}

class OAuthToken {
     //some code
}

?>

I am inheriting above file in Vzaar.php file which is with in same namespace and it's code is as below

    <?php
    namespace RT\AuthBundle\DependencyInjection\Vzaar;

    /*require_once 'OAuth.php';
    require_once 'HttpRequest.php';
    require_once 'AccountType.php';
    require_once 'User.php';
    require_once 'VideoDetails.php';
    require_once 'VideoList.php';
    require_once 'UploadSignature.php';*/

    use RT\AuthBundle\DependencyInjection\Vzaar\OAuth;
    use RT\AuthBundle\DependencyInjection\Vzaar\HttpRequest;
    use RT\AuthBundle\DependencyInjection\Vzaar\AccountType;
    use RT\AuthBundle\DependencyInjection\Vzaar\User;
    use RT\AuthBundle\DependencyInjection\Vzaar\VideoDetails;
    use RT\AuthBundle\DependencyInjection\Vzaar\VideoList;
    use RT\AuthBundle\DependencyInjection\Vzaar\UploadSignature;
    //use RT\AuthBundle\DependencyInjection\Vzaar\OAuth\OAuthConsumer;

    Class Profile
    {
       public static function setAuth($_url, $_method = 'GET')
       {
        $consumer = new OAuthConsumer('', '');
            //some code
       }
    }
?>

Creating new object of OAuthConsumer class throws error that

Fatal error:  Class 'RT\AuthBundle\DependencyInjection\Vzaar\OAuthConsumer' not found in /var/temp/rt-web/src/RT/AuthBundle/DependencyInjection/Vzaar/Vzaar.php

1/1 ClassNotFoundException: Attempted to load class "OAuthConsumer" from namespace "RT\AuthBundle\DependencyInjection\Vzaar" in /var/temp/rt-web/src/RT/AuthBundle/DependencyInjection/Vzaar/Vzaar.php line 378. Do you need to "use" it from another namespace?

Solution

  • Because since 2.1 Symfony uses composer, and composer uses PSR-0/PSR-4 to autoloading the classes, you have to follow the namespace convention, so you have to create those classes in separate files and in the right directory structure, what is represented in the namespace.

    EDIT

    As Cerad mentioned in the comment, you can specify a class map in composer, although what is considered as a best practice with symfony projects, create every class in a separate file.