view raw
user13955 user13955 - 8 months ago 61
PHP Question

Composer: looking for namespaced class in multiple locations

I'm trying to figure out how to get composer to look for classes for a specific namespace under 2 directories. What I'm thinking of is this:

Default location: /src/MyModule/myClass.php
Override location: /config/override/MyModule/myClass.php

Now, I'd like to use composer to configure the autoloader to check if a class exists under the Override location. If it does, use this class. If not, load the class from the default location.

Is this possible using composer or would I have to implement this logic using my own autoloader?


From Composer documentation:

If you need to search for a same prefix in multiple directories, you can specify them as an array as such:

    "autoload": {
        "psr-4": { "Monolog\\": ["src/", "lib/"] }

You would add that to your composer.json file of course. To do it programatically you can do this:

$autoloader = require __DIR__.'/../vendor/autoload.php';

$autoloader->addPsr4('MyModule\\', [ '/first/dir/MyModule', '/another/dir/MyModule' ]);