Generic registerNamespaces in multi module application

Hi!

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();

$loader->registerDirs(
    array(
        $config->application->componentsDir,
        $config->application->pluginsDir,
    )
)->register();

$loader->registerNamespaces(array(
    'Phalcon' => '/vendor/phalcon/incubator/Library/Phalcon',
    'Api\Controllers' => '/app/modules/api/controllers/'
));

$loader->register();

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();

    $loader->registerNamespaces(array(
        'User\Controllers' => __DIR__ . '/controllers/',
        'User\Models' => __DIR__ . '/models/',
        'Components'    => __DIR__ . '/../../components/',
        'Api\Controllers' => __DIR__ . '/../api/controllers/',
    ));

    $loader->register();
 }

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



27.6k
edited Jan '15

Hi,

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:

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


1.1k

Hi,

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?



5.6k

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

$loader->registerNamespaces(array(
    'VendorName' => 'app/'
), true);

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