Adding Namespaces to Your Dispatcher for Phalcon 5

Tony Mucci
Code Kings
Published in
2 min readNov 7, 2023

--

https://unsplash.com/photos/assorted-handheld-tools-in-tool-rack-t5YUoHW6zRo

If you are using namespaces in your Phalcon application, you will need to make sure that your dispatcher is aware of them. This is because the dispatcher is responsible for loading and executing the controllers in your application. If the dispatcher does not know about the namespace of a controller, it will not be able to load it.

There are two ways to add namespaces to your dispatcher:

Using the setDefaultNamespace method

The setDefaultNamespace method allows you to specify a default namespace for all of the controllers in your application. This means that you will not need to explicitly specify the namespace for each controller in your routes.

To use the setDefaultNamespace method, you can do the following:

use Phalcon\Mvc\Dispatcher;

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

Using the setNamespaceName method

The setNamespaceName method allows you to specify the namespace for a specific controller. This is useful if you only want to use namespaces for some of your controllers. This method is what I am using since using a default is a bit too heavy handed.

To use the setNamespaceName method, you can do the following:

use Phalcon\Mvc\Dispatcher;
$dispatcher = $di->get('dispatcher');
$dispatcher->setNamespaceName('MyApp\Admin\Controllers');
$dispatcher->setControllerName('Index');
$dispatcher->setActionName('index');
$dispatcher->dispatch();

Using the dispatch method

The dispatch method is used to execute the controller and action that have been specified.

To use the dispatch method, you can do the following:

PHP

$dispatcher = $di->get('dispatcher');
$dispatcher->dispatch();

Grand Finale

The following code snippet shows how to dispatch a controller and action using the dispatcher and router:

$dispatcher = $di->get('dispatcher');
$dispatcher->setNamespaceName($router->getNamespaceName());
$dispatcher->setControllerName($router->getControllerName());
$dispatcher->setActionName($router->getActionName());
$dispatcher->setParams($router->getParams());
$dispatcher->dispatch();
$response = $dispatcher->getReturnedValue();

This code snippet first gets the dispatcher from the dependency injection container. Then, it sets the namespace, controller name, action name, and parameters for the dispatcher using the router object. Finally, it dispatches the controller and action, and stores the returned value in the $response variable.

Happy Coding!

--

--

Tony Mucci
Code Kings

Co-founder of SimpliCourt, dree, My Company Tools, and Eklect Enterprises