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

Redirect to controller name / action name

After working with CakePHP I've gotten used to doing HTTP redirection like this:

$this->redirect(array(
    'controller' => 'controller_name',
    'action' => 'action_name'
))

This way if the URL to that controller/action changed in the future, I wouldn't have to change all the instances that referenced this route. A URL may be subject to change in the future, while an action name rarely changes.

It seems in Phalcon I can only do

$this->response->redirect('controller/action');

But this doesn't redirect to the URL defined in the router. I see there's this this option:

$this->response->redirect(array(
    'controller' => 'controller_name',
    'for' => 'action'
));

But this doesn't work, because the 'for' key must be meant for something other than an action name.

Have you tried using forwards?

 $this->dispatcher->forward(array(
            "controller" => "controller_name",
            "action" => "action",
            "params => array(1,2,3)
        ));

Similar to a redirection but doesn't reload page.

Calling that redirect method doesn't immediately redirect the user. You should return $this->response right after you call the redirect method.



5.7k

When you use the array syntax and the for key as in your third example, the value of that key will be the name of the route phalcon will look for.

If you name your routes using $myRoute->setName('my_route_name');, you will then be able to do the following in your controllers:

$this->response->redirect([ "for" : "my_route_name" ])->send();
exit();

I usually use exit(); after the redirect. Just to make sure it doesn't go beyond that no matter what.