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

Controllers In Sub-Folders

Do I have to register every sub-folder under controllers to be able to use the controller ?

/pub/index.php

$loader->registerNamespaces([
    'App\Controllers' => '../app/controllers/',
    'App\Controllers\Example' => '../app/controllers/example/',
    'App\Libraries' => '../app/libraries/',
    'App\Models' => '../app/models/'
])->register();

$di->set('dispatcher', function() {
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    $dispatcher->setDefaultNamespace('App\Controllers');
    return $dispatcher;
});

/app/controllers/example/TestController.php

namespace App\Controllers\Example;

class TestController extends \Phalcon\Mvc\Controller {

    public function indexAction() {
        echo 'TestController.php in Public Folder.';
    } #index

}

/app/routes.php

$router->add('/:controller/:action/:params', [
    'namespace' => 'App\Controllers\Example',
    'controller' => 1,
    'action' => 2,
    'params' => 3,
]);

$router->add('/:controller', [
    'namespace' => 'App\Controllers\Example',
    'controller' => 1
]);

without using this line its not working.

'App\Controllers\Example' => '../app/controllers/example/',

I get this error;

Phalcon\Mvc\Dispatcher\Exception: App\Controllers\Example\TestController handler class cannot be loaded


7.9k

Hi,

You better read PSR4 autoloading standard : https://www.php-fig.org/psr/psr-4/



2.1k
Accepted
answer

If you haven't defined

'App\Controllers\Example' => '../app/controllers/example/'

Phalcon will create the path to the folder using the 'Example' part of the namespace and the rule below:

'App\Controllers' => '../app/controllers/',

meaning you end up with '../app/controllers/Example/'