We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

DB routing in multi-module site

Hello!

I have a multi-module app (modules: Core, Admin and Site) where Core module contains a certain model i would like to use in the router.

I'm not sure what is relevant and what isn't for you to help me with this.

In index.php I'm setting up services first (including the router), which are then passed to \Phalcon\Mvc\Application. Application then registeres modules:

$application->registerModules(
        'core' => [
            'className' => 'Project\Core\Module',
            'path' => APPROOT .'/modules/Core/Module.php'
        ],
        'admin' => [
            'className' => 'Project\Admin\Module',
            'path' => APPROOT .'/modules/Admin/Module.php'
        ],
        'site' => [
            'className' => 'Project\Site\Module',
            'path' => APPROOT .'/modules/Site/Module.php'
        ]
)

I tride to use model from the Core module, like so:

$myModel = new Project\Core\Models\MyModel();

I just get the error that Model is not found. But it works for:

$router->mount(new Project\Core\Routes());

I don't understand why won't models work in the router. If I try to instantiate the same model somewhere else, it works as expected.

The namespaces registered in registerNamespaces method of module will be fired once they will be used in routing. This means that you need to register model namespaces outside of modules, like in bootstrap file for example.



12.1k
edited Dec '17

In my multimodule structure I have defined common namespaces and common services used all over my application in config/loader.php and config/services.php and then I include them inside all module definitions. The namespace of your core models should be defined inside this common file.

edited Dec '17

You need to register the namespace from the module you want.

    public function registerAutoloaders(DiInterface $di = null) {
        $loader = new Loader();
        $loader->registerNamespaces([
            'Project\\Core\\Models\\MyModel' => $this->config->application->modelsDir,
        ], true);
        $this->registerFiles('vendor/autoload.php');
        $loader->register();
        $di['loader'] = $loader;
    }