How to use Composer to autoload classes from outside the vendor?
Asked Answered
C

1

17

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.

Crocidolite answered 31/1, 2015 at 15:16 Comment(6)
Can't you simply use the files or classmap autoloader? getcomposer.org/doc/04-schema.md#autoloadJeopardize
Yup, files or classmap should do the trick.Wendy
No, because i can't select folders from outside vendor folder in autoload section.Crocidolite
I need composer to autoload classes by absolute path (not by patch IN vendor directory).Crocidolite
"This loads classes from..." not it does not making this question impossible to answer, because it is based on incorrect assumptions.Loiretcher
Why should any package reference classes that are not part of that package? What if that package is used in another context where such classes are not defined?Antirachitic
A
38

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

Antipodes answered 2/2, 2015 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.