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

Call a notFound router action

There is more than one situation when 404 is needed. For example, when user try to get access by the route allowed for Ajax only. So it would be useful to be able to call notFound manually. Is there any way for this?



29.4k

How about forward?

if(!$this->request->isAjax())
{
    $this->dispatcher->forward(array(
        "controller" => "error",
        "action"     => "notFound"
    ));
}


29.4k

or better smthg like this

$router->add('/404', [
    'module'     => 'frontend',
    'controller' => 'error',
    'action'     => 'notFound',
])->setName("404");

// next code is inside controller
$route404 = $this->router->getRouteByName('404');
$this->dispatcher->forward($route404->getPaths());

Or you can use same solution as this forum to display error messages: https://github.com/phalcon/forum/blob/master/app/controllers/IndexController.php Try https://forum.phalcon.io/argefgaregrgaerg Just put check for ajax request as in Agent-J first code snippet if(!$this->request->isAjax()) or if you have controllre which handle only ajax requests, then you can place this check in initializre method which is executed automatically: https://docs.phalcon.io/en/latest/reference/controllers.html#initializing-controllers



29.4k

then you can place this check in initializre method

Its better use beforeDispatch method



32.5k

Second Agent-J solution looks fine. I just want to provide single operation sequence for any possible 404 response. setStatusCode() or etc. could be placed to a action's method, but the names of the action and controller are not wanted by me to be written for any 404 need.

I think that not found handling could be implemented a bit better in the framework. Lets remember auto not found for unmatched route but need of user implemented one for matched route and unfounded controller. According to the specification, the 404 response is sent for any request doesn't provide any data to response. This could be service links (ajax-only) or private/protected app parts accessed by GET, invalid route params, unfounded controller/action, unfounded file, many special realization-related cases like unfounded post/message/user or any other data in database and so on and so on. And current "errors system" isn't very handy to provide good solution for some part of this cases.

Yes, problem could be solve some way with current capabilities, but it would looks like "crutches" (as such ways called in russian community =)