Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Autoloader multi modules override

Hi all,

On a multi-module application I'm triying to share services, but it seems that the autoloader defined in each Module.php works overriding the global one. For example:

I use a global loader for the application on the bootstrap.

<?php
$loader = new \Phalcon\Loader();

    $loader->registerNamespaces(array(
        'MyApp\Base\Controllers' => __DIR__ . '../apps/base/controllers/'
    ));

    $loader->register();

And new loaders on each module. (using Module.php)

<?php
public function registerAutoloaders(DiInterface $dependencyInjector = NULL)
    {
        $loader = new \Phalcon\Loader();

        $loader->registerNamespaces(array(  'MyApp\User\Controllers' => __DIR__ . 'controllers/'
    ));

    $loader->register();
}

if I load the base module as default then MyApp\Base\Controllers are accesible. But they become unreachable when I use another module with its own autoloader and namespace.

Is the a way to avoid using a global autoloader for all my modules? Can I add namespaces to a global autoloader or stack them during process time?

first post so I would like to thank you all, the Phalcon Framework community, for all your efforts.



7.3k
Accepted
answer

You can't use any loaders in application. Remember PSR and jusy namespaces register.

$loader = new \Phalcon\Loader();

$loader->registerNamespaces([
    'Apps' => \dirname(__DIR__) . DS . 'Apps' . DS,
]);

in your bootstrap (paublic/index.php)

for all classes of your application, any custom included.

Apps/
├── Api
│   └── Controllers
├── Backend
│   ├── Controllers
│   └── Views
│       └── Index
├── Caservice
├── Config
├── Frontend
│   ├── Controllers
│   └── Views
│       ├── Ghost
│       ├── Index
│       ├── Inventory
│       ├── layouts
│       ├── Manufacturers
│       ├── Part
│       └── partials
├── Models
└── Var
    └── Compiledviews
        ├── Backend
        └── Frontend

Just 1 string and all classes.

thanks @Oleg it worked. In any case I'm finally using composer to autoload all my namespaces etc.