Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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


5.7k

Hi,

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



1.9k
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/'