CakePHP and clean URLs

Posted by Jason on July 28, 2007 at 11:39 am

Now don’t get me wrong - I love CakePHP and I know there’s a good reason for the controller/action format of urls. In fact I often find it helps to have a framework that forces that sort of thinking on me all the time since most of the sites I write are more application than website. It’s a bit like the good old days when I was struggling to get my head around the concept of OO after coming from a very procedural background. I could probably have done with a framework then too.

So I do think that it’s great for web applications, but not necessarily for web sites. Clean urls have many touted advantages over controller/action urls for a web site. I’m not sure how many are true (things like Google favouring them seem like a good reason, if that is actually the case) but for me it’s best simply because they are not controller actions. A ‘contact me’ page is a ‘contact me’ page. It’s not really an action on a particular controller in your application. An ‘about’ page is similar - it just seems wrong to say ‘about’ is an action on ‘pages’. Well, it does to me anyway. Whilst I usually write web applications there is almost always a web site component like this to them and I think it’s fine to seperate those two concepts even when they’re on the same site.

Now it’s true that you can write static pages directly to the webroot, but my clients almost always want some management control over those pages. As much as I’d like them to have to come back to me every time they want to change a word it just doesn’t seem particularly fair and just harms my chances of repeat business! All of the other solutions I came across just seemed rather complex and often slightly dodgy. So I came up with a simple solution of my own that works fine.

Basically you add an entry to routes.php for each of these pages:

$Route->connect('/contact/*', array('controller' => 'pages', 'action' => 'contact'));

This will redirect any call to ‘/contact’ to ‘/pages/contact’, but without giving that fact away to the user. It’s true that you can’t now have a controller called ‘contact’ but then you wouldn’t want one anyway (the main reason being controller names should be plural when following the Cake conventions!). You can add as many of these lines as you like. If you end up with more than 2 or 3 you might want to question whether those pages should have been part of a controller!

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment