Using Composer's Autoload

后端 未结 6 636
挽巷
挽巷 2020-11-30 19:55

I have been looking around the net with no luck on this issue. I am using composer\'s autoload with this code in my composer.json:

\"autoload\":         


        
6条回答
  •  再見小時候
    2020-11-30 20:25

    In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.

    I was looking to autoload my package files using composer which I have under the dir structure given below.

    
        |--------src/
        |           |--------App/
        |           |
        |           |--------Test/
        |
        |---------library/
        |
        |---------vendor/
        |           |
        |           |---------composer/
        |           |           |---------autoload_psr4.php
        |           |           
        |           |----------autoload.php
        |
        |-----------composer.json
        |
    

    I'm using psr-4 autoloading specification.

    Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.

    "autoload": {
            "psr-4": {
                "OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
            }
        } 
    

    This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -

    namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration
    
    use OrgName\AppType\AppName\Controller\Provider\User; // when using the class
    

    Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php

    Now if composer is installed properly all that is required is #composer update

    After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php

    $vendorDir = dirname(dirname(__FILE__));
    $baseDir = dirname($vendorDir);
    
    return array(
        'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
        'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
    );
    

    This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php

提交回复
热议问题