We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Generic registerNamespaces in multi module application


I'm developing a multi-module app with phalcon. I have common elements and I want register only one time.

For example:

in /app/config/loader.php (charged in index.php):

$loader = new \Phalcon\Loader();


    'Phalcon' => '/vendor/phalcon/incubator/Library/Phalcon',
    'Api\Controllers' => '/app/modules/api/controllers/'


I need add 'Api\Controllers' => '/app/modules/api/controllers/' namespaces for all modules. I try to add in /app/config/loader.php, but the app not found the Controller.

The solution is add it in Module.php for all modules:

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

        'User\Controllers' => __DIR__ . '/controllers/',
        'User\Models' => __DIR__ . '/models/',
        'Components'    => __DIR__ . '/../../components/',
        'Api\Controllers' => __DIR__ . '/../api/controllers/',


There are any posibility to add all common Namespaces only in /app/config/loader.php ??

edited Jan '15


in /app/config/loader.php; I think that the way you declare directories in the namespaces loader is wrong. To check that, watch if you can access to one of the incubator library.

something like in /app/config/loader.php:

    'Phalcon' => '/vendor/phalcon/incubator/Library/Phalcon', //looks bad
    'Api\Controllers' => __DIR__ . '/../../app/modules/api/controllers/' // sounds better ;-)



But do I have to write every namespace for all folders controlles and models of each module?

Can I use a regular expression to declare the same path, but only changing the module name?


Its better you follow PSR4 Autoload, it will save your time

    'VendorName' => 'app/'
), true);

Its automatically load your files in app folder if you follow PSR4 autoloader format