Robin71
Robin71

Reputation: 403

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?

Upvotes: 4

Views: 1358

Answers (2)

yergo
yergo

Reputation: 4980

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');
    }
}

Upvotes: 5

Nikolay Mihaylov
Nikolay Mihaylov

Reputation: 3876

I would recommend forwarding user to 404 page via Dispatcher. This way the URL will remain and you will do everything according to SEO rules.

public function initialize() {
    if (!$this->request->isAjax()) {
        $this->dispatcher->forward(['controller' => 'error', 'action' => 'show404']);
    }
}

Also it's not a good idea to make redirects in initialize. More info from Phalcon here: https://forum.phalconphp.com/discussion/3216/redirect-initialize-beforeexecuteroute-redirect-to-initalize-and

Adding my 404 method in case someone needs it. It demonstrates correct header handling (again for SEO purposes)

// 404
public function error404Action()
{
    $this->response->setStatusCode(404, 'Not Found');
    $this->view->pick(['templates/error-404']);
    $this->response->send();
}

Upvotes: 0

Related Questions