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

How can I get ControllerName and ActionName form the /public/index.php file?

$di = new Phalcon\Di\FactoryDefault();
$di->set("hello", function () {
    $ControllerName = '???';
    $ActionName = '???';
    return $ControllerName.'__'.$ActionName;
});

How can I set the $ControllerName and $ActionName variables?



79.0k
Accepted
answer
edited May '16

You need to inject proper service which will give you that information. In this case, that service/component is the Router object.

// Getting the processed controller
echo $router->getControllerName();

// Getting the processed action
echo $router->getActionName();

// Get the matched route
$route = $router->getMatchedRoute();

So, in your example service named "hello" , you need to provide visibility to IoC ($di).

$di = new Phalcon\Di\FactoryDefault();
$di->set("hello", function () use ($di) {
// first, resolove Router
$router = $di->getShared('router');

// Getting the processed action
$router->getActionName();

// Get the matched route
$route = $router->getMatchedRoute();

// change your code however you need further...

    $ControllerName = '???';
    $ActionName = '???';
    return $ControllerName.'__'.$ActionName;
});

Also if you are using phalcon 2.1.x you don't need to do use ($di), you can just access it using $this in service definition.