Shift8 Creative Graphic Design and Website Development

Redirect to Anywhere Using Closure with Lithium Router

Posted by Tom on Mon, Jan 03 2011 15:07:00

One of my New Year's resolutions is to post more to my blog. Even if it's short posts. That's fine. So to that effort, I'll leave you all with a little quick tip for the Lithium framework. If you want to redirect a request to an external server or any URL you can do so in one of two ways.

Redirect Controller Action
The first method is how you might do it with the CakePHP framework...Simply route all your URLs to a controller that has an action which will call $this->redirect() and pass the argument (the URL you wish to redirect to). That might look like this:

Router::connect('/about', array('controller' => 'Redirects', 'action' => 'go_to_url');

Then you'd need your "RedirectsController" to have a method something like this:

... 
public function go_to_url($url="/") {
    $this->redirect($url);
}
...

That's great and will work but there's actually a bit more involved. First off, you have to have some extra controller (which could handle all sorts of "legacy" issues if migrating from an old codebase, so that's fine if you want to do so) and that means a bit more code than necessary in most cases. You might also have to tell it not to use a template, etc. 

Router Closure
If you didn't know already, Lithium allows for closures in its Router::connect() method. It's very very nice. So here's what you can do instead: 

Router::connect('/about', array() function() {
    header('Location: http://www.site.com/about.html');
    exit; 
});

That's all there is to it. With this method, you are also bypassing a good chunk of the framework, so it should perform a bit better too. You can get a little clever there and add some code to check if the URL exists and if not, re-direct to a 404 page on your server or something too. Go wild Tongue out


[Back To Blog Index]