How to I use Composer to autoload classes from outside the vendor?

只愿长相守 提交于 2019-11-26 11:07:08

问题


I use psr-4 autoloader from composer:

\"autoload\": {
    \"psr-4\": {
        \"DG\\\\Munchkin\\\\\": \"src/DG/Munch/\"
    }
}

This loads classes from /var/www/html/xxx/vendor/yyy/src/DG/Munch

But how can I load classes from /var/www/html/xxx/?

I wrote my own autoloader, but when I require vendor/autoload.php (composer autoload) and my autoloader, it won\'t work until I create instance of a class in my own autoloader.


回答1:


The src directory would be in your project root. Its on the same level as vendor directory is.

If you define

"autoload": {
    "psr-4": {
        "DG\\Munchkin\\": "src/DG/Munch/"
    }
}

this will not load classes from /var/www/html/xxx/vendor/yyy/src/DG/Munch, like you stated.

Because your project structure is:

/var/www/html/
 +- /xxx (project)
     - composer.json
     +- /src
        +- DG
           +- Munch
     +- /vendor
        - autoload.php
        +- vendor-projectA
        +- vendor-projectB
        +- yyy

The \DG\Munchkin namespace would map to classes inside

/var/www/html/xxx/src/DG/Munch and not inside

/var/www/html/xxx/vendor/yyy/src/DG/Munch.

But how can I load classes from /var/www/html/xxx/?

Define the paths in the composer.json (inside /var/www/html/xxx/) of your project:

"autoload": {
    "psr-4": {
        "ProjectRoot\\" : "", 
        "NamspaceInSourceDir\\" : "src/"         
    }
 }

or load the composer autoloader in your index.php or during it's bootstrap and add the paths manually:

$loader = require 'vendor/autoload.php';
$loader->add('Namespace\\Somewhere\\Else\\', __DIR__);
$loader->add('Namespace\\Somewhere\\Else2\\', '/var/www/html/xxx');

Referencing: https://getcomposer.org/doc/04-schema.md#autoload



来源:https://stackoverflow.com/questions/28253154/how-to-i-use-composer-to-autoload-classes-from-outside-the-vendor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!