Geoff Garbers

Husband. Programmer. Tinkerer.

Static pages in CakePHP

Jun 01, 2011

I was doing some general Twittering this morning, and came across I’ve been on this site quite a few times before, and I’ve really found the posts in it to be really useful.

However, there was a specific post that I came across that really piqued my interest. This was how to deal with static pages in CakePHP. You can read the post here. As useful as I found the post, I’m all for massive automation. So I did some more digging into the Router class, to figure out how I could wildcard this and use it for any static page (without having to manually specify the list of pages).

Unfortunately, due to the way the regular expressions for matching routes are compiled, it’s not possible. So, I came up with a more automated way of generating the list. It requires a bit more PHP processing than the manual specified by teknoid, but it makes the process far more automatic (assuming you always have a view file in VIEWS/pages for the page).

$availablePages = glob(VIEWS . 'pages' . DS . '*.ctp');
if ($availablePages) {
	$extensions = array_pad(array(), count($availablePages), '.ctp');
	$availablePages = array_map('basename', $availablePages, $extensions);
	Router::connect('/:page', array('controller' => 'pages', 'action' => 'display'), array('page' => implode('|', $availablePages), 'pass' => array('page')));

And that, right there, is my more automated solution. It now helps with the automagic creation of static page URLs, without the “/page/page-name” in the URL.

Thanks to teknoid for the original blog post.