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 subfolders

I try to create application with structure:

\app\controllers\ \app\controllers\api\

in api folder I want to put my api controlles. And I want request url: localhost/api/apicontroller/method that run specified api method. How I understand I need use phalcon routes but I don't understand how. I try something like this (but it not work):

$di->set('router', function() {
    $router = new Phalcon\Mvc\Router();
    $router->add('/api/contoroller/method', array("controller" => "api\contoroller", "action" => "method"));
    return $router;
});

I now, that phalcon support modules (https://docs.phalcon.io/en/latest/reference/routing.html#routing-to-modules) but it's not what I need.

Thanks!

Hi,

to make the routing work as expected you have to use the placeholders ":controller" and ":action" (note the leading doublecolon). In the options array you then use the index of the placehloder. Try something like

$router->add(
    "/api/:controller/:action",
    array( "controller" => 1, "action" => 2, "namespace" => "Application\API\\")
);


2.2k

Thank you! It work fine for me!