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

Auto registration modules

Hi! I did automatic registration modules:

$modules = array();

foreach(array_diff(scandir(APP_DIR), array('..', '.')) as $dir)
{
    if(is_dir(APP_DIR.'/'.$dir))
    {
        $modules[$dir] = array(
            'className' => 'Cms\Module\\'.ucfirst($dir),
            'path' => '../modules/'.$dir.'/Module.php'
        );
    }
}

$application->registerModules($modules);

Is there a better solution?

What is the difference these two methods?

1.

$application->registerModules(
        array(
            'frontend' => array(
                'className' => 'Multiple\Frontend\Module',
                'path'      => '../apps/frontend/Module.php',
            ),
            'backend'  => array(
                'className' => 'Multiple\Backend\Module',
                'path'      => '../apps/backend/Module.php',
            )
        )
    );

2.

$application->registerModules(
    array(
        'frontend' => function($di) use ($view) {
            $di->setShared('view', function() use ($view) {
                $view->setViewsDir('../apps/frontend/views/');
                return $view;
            });
        },
        'backend' => function($di) use ($view) {
            $di->setShared('view', function() use ($view) {
                $view->setViewsDir('../apps/backend/views/');
                return $view;
            });
        }
    )
);


98.9k

I think your solution works but it's not optimal, unless you have a lot of modules adding a scandir in every request does not seem like a good idea.

Manual registration requires no filesystem stats, using the first solution you can move module registration to independent files per module (Module.php) or you can put the module registration in a single file using the second option (anoymouse functions).

How can I move module registration to independent files per module (Module.php)?

Whether good solution to store data about the modules in the database? Better than the method of scandir () or not?