A simple redirect component
I already wrote about doing a redirect with Ajax. Now, I created a simple component from that code I presented there:
// app/controllers/components/redirect.php
class RedirectComponent extends Object
{
var $controller;
var $components = array('RequestHandler');
function startup(&$controller)
{
$this->controller =& $controller;
}
function goto($url)
{
if ($this->RequestHandler->isAjax())
{
$this->controller->set('url', $url);
}
else
{
$this->controller->redirect($url);
}
}
}
The usage is easy. Add the component to the components array:
var $components = array('Redirect');
Afterwards you can use it in the following way:
$this->Redirect->goto('/mycontroller/myaction');
Do not forget do add the code snippet to your view which necessary to do the javascript redirect:
<?php if (isset($url)) echo $javascript->codeBlock('window.location = "'.$url.'"'); ?>
Update (2006-04-03): Small bug fixed in startup function.




I don’t understand useful of “startup” method. Can you give me exemple ?
We must call it manually before redirect, it right ?
The startup function is automatically called by Cake, you do not have to call it yourself.
If all you want to do is redirect, I find it much more convenient to eliminate if (isset($url)) from views. To do that, I modified goto function to following:
function goto($url)
{
if ($this->RequestHandler->isAjax()) {
echo ”;
echo ‘window.location = “‘.$url.’”‘;
echo ”;
exit();
} else {
$this->controller->redirect($url);
}
}
I use this in admin section to redirect to login form if session has expired.
Thanks for this great site cakebaker.
@nnc: Thanks for the addition.
When I run this code, I get the following error:
Fatal error: Call to a member function redirect() on a non-object in /path/to/app/controllers/components/component.php on line 18
Line 18, in my case is:
$this->controller->redirect(’/users/login’);
Any ideas? I’m pulling my hair out.
@Aaron: Hm, strange, it works here. It looks like the controller is not set. Does the startup() method get called?