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

phalcon namespaces not working for me

i just started a new project but cant get namespaces to work in phalcon i have never had this issue before if i remove the namespace its working fine.

Loader.php

<?php

$loader = new \Phalcon\Loader();

$loader->registerDirs(
    [
        $config->application->controllersDir,
        $config->application->modelsDir
    ]
    );

 $loader->registerNamespaces(
    [
        'App\Controllers' =>   $config->application->controllersDir,
        'App\Models'      =>   $config->application->modelsDir,
    ]
    )->register();

config.php

return new \Phalcon\Config([
    'database' => [
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => 'root',
        'dbname'      => 'test',
        'charset'     => 'utf8',
    ],
    'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/Controllers/',
        'modelsDir'      => APP_PATH . '/Models/',
        'migrationsDir'  => APP_PATH . '/Migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'cacheDir'       => BASE_PATH . '/Cache/',
        'baseUri'        => '/',
    ]
]);

IndexController.php

<?php
declare(strict_types=1);
namespace  App\Controllers;

class IndexController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {

    }

}
edited Aug '20

I cleaned up your code blocks. Please read the Help to find out more.

What does "not work" mean? What is failing and what have you tried?

One common gotcha when namespacing controllers is you have to set the default namespace in your dispatcher: https://docs.phalcon.io/3.4/en/namespaces#controllers-in-namespaces (look at the code block right above the header)

edited Aug '20

Paths with uppercase. Should be:

return new \Phalcon\Config([
    'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir'      => APP_PATH . '/models/',
        'migrationsDir'  => APP_PATH . '/migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'cacheDir'       => BASE_PATH . '/cache/',
        'baseUri'        => '/',
    ]
]);