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

Get controller/action for some URL at runtime

Can I manually get the controller and action which will be executed for some URL? I mean exactly controller/action which will be executed if I request this URL, considering configs (defaults), router rules etc.

Actually I want to know if some URL is accessible for current user.

<?php if (canAccess($current_user_role, "/products/add/")) { // HOW ???
    echo $this->tag->linkTo(["/products/add/", "Add a product"])
} ?>
//assuming that you have filled your complete route to $di['router']
$router = $di['router'];
$router->handle("/products/add/");

$dispatcher = $di['dispatcher'];
// Pass the processed router parameters to the dispatcher
$dispatcher->setControllerName($router->getControllerName());
$dispatcher->setActionName($router->getActionName());
$dispatcher->setParams($router->getParams());
try{
    // Dispatch the request
    $dispatcher->dispatch();
    echo "Dispatch seems to work"
}
catch($e){
    echo "Whooa cannot access:".$e
}   


32.4k

Looks like I have to make another instance of a dispatcher for this. To do not break performance of the running request. Hope it will not be too slow to use such way.



32.4k

Nope. Dispatcher acts the response service and... isn't intended to be used such way... Or it will requires a separated copy of whole application instance with DI and services.

Looks like I have to do all this by hand. Check existent of class/method with reflections etc.

I think we should have a simpler solution for this. You can make a simple lookuptable, that the key is the controller and action name, and the value is the role/user is able to access that controller/action.

function canAccess($url, $roleId){
    $this->router->handle($url);
    $whoCanAccess =  $this->lookup[$router->getControllerName().$router->getActionName()];
    return in_array($roleId,$whoCanAccess);
} 

Have you read the docs about acl? https://docs.phalcon.io/en/latest/reference/acl.html The acl approach would be more powerful than using plain lookup table. but the basic idea is the same



32.4k

Yeah, I had tangled a little first time. But you had forwarded me on a right way. Actually, router provide enough information about a url for my issue. Because ACL stores only strings. Same strings which I get from router when handle a url. So I have same information which have when check access for any common request. Thank for discussion. Sometimes mind really got stacked on such trivial things when you trying to make it "short and simple" and it want becomes even more complicated : D