The Secret of CakePHP Advanced Routing – Even Better URLs

Page content

The power of CakePHP has a lot to do with conventions. The framework (like many others) harnesses its power by enforcing certain conventions and standards that users must follow. You name your database tables, file names, etc; a particular way and boom, models, views and controllers are automatically created and ready for use. This is the beauty of the MVC structure. Your URLs also follow thing structure:

Straying From Convention

But sometimes, conventions suck. Sometimes you want greater control over things, but still don’t wanna do them from scratch. The strictness of the MVC structure dictates how your URLs will look. Consider this: CakePHP has a basic pages controller, which you can use when you don’t need a model or controller. You just enter the view and voila , a page. But your pages have a URL of:

Wouldn’t you rather:

The Routes Configuration examples in the CakePHP manual are a bit simple. Here’s how to use a bit more advanced routing:

Router::connect('/(.*).htm', array('controller' => 'pages', 'action' => 'display'));

This says, consider everything that comes in with an HTM extension and send the URL as a parameter to the display action on the pages controller.

The idea was stolen from Lumad CMS. They use the following in Rewrite in .htaccess for their pages:

RewriteRule ^~(.*) content_pages/displayurl/$1 [L]

They use a prefix of ‘~’ instead of a suffix of ‘.htm’, but you get the picture. I’m sorry to disappoint you, I’m not as creative as you thought.

How I Use Advanced Routing

I maintain a makeshift CMS using CakePHP. In this project I have a basic model (contents) with a title and body fields, among others. I would use the pages controller, but I need end users to be able to end pages through the database.

Router::connect('/(.*).htm', array('controller' => 'contents', 'action' => 'view'));

Conventions are great as long as they don’t get in the way. The great thing about CakePHP is that they frequently provide ways to get what you need done easily.

Make your static content look like static pages with Advanced routing.

Source: Routes Configuration [CakePHP Manual]