Robin71 Robin71 - 5 months ago 23
PHP Question

PhalconPHP - redirect in initialize()

In my project I've created AjaxController which operated ajax requests.
I'd like to user which enter to url used by ajax get 404 error.
In AjaxController.php I have:

public function initialize() {
if (!$this->request->isAjax()) {
return $this->response->redirect('error/show404');
}
}


(Of course I have ErrorController with show404Action)

It doesn't work. When i enter to example.com/ajax in browser I get content from IndexAction in AjaxController. How to repair it?

Answer

Please try to do the same in beforeExecuteRoute(). Phalcon's initialize() is designed, as its name says, to initialize things. You can dispatch there using dispatcher, but should not redirect.

You can check part of documentation here. Column "can stop operation?" says if it is possible to return response object to complete request or false to stop evaluate to other methods and compile view.

One precious to know thing is that beforeExecuteRoute() executes every time before action is called, so may fire couple of times in case you are forwarding between your actions.

public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
{
    if (!$this->request->isAjax()) {
        return $this->response->redirect('error/show404');
    }
}
Comments