Home > other >  Autoloading nested files?
Autoloading nested files?

Time:02-20

In my Laravel package I have some of my model traits under /src/Models/Traits.

The src folder is autoloaded in composer.json:

"autoload": {
        "psr-4": {
            "Acme\\Package\\": "src"
            ......

Therefore any file under src can be used in the packages parent application by:

use Acme\Package\SomeHelper;

Is there a way to keep my traits under /src/Models/Traits but have them accessible in parent applications like:

use Acme\Package\SomeTrait;

CodePudding user response:

The documentation for Composer includes this statement:

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

So in your example, you could specify two directories to search like this:

{
    "autoload": {
        "psr-4": { 
             "Acme\\Package\\": ["src", "src/Models/Traits"]
        }
    }
}

As an aside, in case it's not clear, use statements and autoloading are unrelated features. The use statement allows for aliasing/importing a namespaced name within a particular file, and is processed as a string replacement by the compiler without any reference to the class or trait definition. The autoloader is triggered at run-time when a class, interface, or trait is referenced but hasn't yet been defined. A use statement on its own does not trigger the autoloader.

  • Related