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

Can't get the loader to work with namespaces

I'm on a windows system, trying to get the loader to work.

The scripts current directory was set to "app/" by using chdir()

my app folder looks like this:

app/
  cache/
  config/
  controllers/
  core/
  libraries/
    common/
    plugins/
    util/
  models/
  views/

I parse my config ini like this:

self::$config = new Config\Adapter\Ini(self::CONFIG_INI_FILE_PATH);

it has the following configuration:

[loaderNamespaces] App\Controllers='controllers/' App\Models='models/' App\Libraries\Plugins='libraries/plugins/' App\Libraries\Utli='libraries/util/'

In my core the loader does the following:

$loader = new Loader();
$loader->registerNamespaces(self::$config->loaderNamespaces->toArray());
$loader->register();

Checking the loader with xdebug, shows that all configuration were passed to the loader.

But it wount work. Does anyone have an idea what I'm doing wrong here?



9.2k

The answer was to overwrite the default router with another one like this:

$dependencyInjector->set('router', function() {
  $router = new Router();
  $router->setDefaultNamespace("App\\Controllers");
  return $router;
}, true);

Hello,

If you respect php naming convention, you can simply upper case the first letter of your namespaced directories and set php$loader->registerNamespaces(['App' => realpath(__DIR__ . '/../App')]);

For my part, I have something like this :

$loader->registerNamespaces(array(
        'Zend' => APP_ROOT_PATH . '/server/lib/Zend/',
        'RCV' => APP_ROOT_PATH . '/server/lib/RCV/',
        'XXX' => APP_ROOT_PATH . '/server/app/XXX/',
        'YYY' => APP_ROOT_PATH . '/server/app/YYY/',
        'App' => APP_ROOT_PATH . '/server/app/App/',
        'Chrome' => APP_ROOT_PATH . '/server/lib/Chrome/',
        'Monolog' => APP_ROOT_PATH . '/server/lib/Monolog/',
        'Psr' => APP_ROOT_PATH . '/server/lib/Psr/',
        'Symfony' => APP_ROOT_PATH . '/server/lib/Symphony/',
    ));

$loader->register();

because of multiple external libraries. XXX and YYY are my two namespaced webapp, I will regroup it directly into App to avoid the duplication app/App.

HTH



9.2k

You mean if i keep the directory names equal to the namespaces even in case, i will not have to use my own router?



2.2k
Accepted
answer

Don't see in your initial question that about router, my answer was relative to auto loading by namespaces. Note that Windows OS is case insensitive but Linux OS is case sensitive and namespacing with the same naming convention for class and path is "best practices" and recommended by Zend/PHP conventions : https://framework.zend.com/manual/1.12/en/coding-standard.naming-conventions.html

Regard