Code Snippets

Case Insensitive Routes In CakePHP 1.2RC3

Posted by Matt on Wed, Nov 12 2008

I wrote a post awhile back on how to do case insensitive routing in CakePHP. The method described there doesn't work anymore. The Cake Router now interprets the ":" character as the beginning of a named parameter.

An alternate way, which does work in RC3 is to begin your route with (?i), which will tell the regular expression engine to ignore the case for all characters to the right.

If you want to have an "about" page that is linked to by "/about”, "/About”, or "/aBoUt” you can use:

Router::connect(’/(?i)about’, array(’controller’ => ‘pages’, ‘action’ =>’display’, ‘about’));

I don't believe there is way to set this for all routes, but if there is I would love to hear it.

CakePHP Pagination Recall Component

Posted by Matt on Thu, Jan 24 2008

I've been using the built in pagination in CakePHP 1.2-beta a lot lately and I must say it's freaking awesome. My one oh so minor grievance is that it doesn't "remember" where you were if you navigate off the page. For example many times I'll be paging through a sorted list of records and want to edit a particular one. After I edit and save I'm dropped back to the index with the default sorting on page 1.

I Googled around a bit and skimmed through the pagination code, but didn't see a quick way to turn this type of functionality on. So I wrote a quick component that keeps the sort/page in the session and re-applies it. This is all done automatically by just including the component in your controller.

You can download the component here.

I'll probably submit it to the CakePHP Bakery soon, but was hoping to get some feedback first.

Coding Instead of Croning

Posted by Matt on Sun, May 20 2007

The Setup

At my job one of the products we offer is a radio service. There are a bunch of channels and each channel has a bunch of playlists. I was tasked with writing something to automatically switch the active playlist for each channel. My initial thought was to make a flag in the database marking the active playlist and then write a script that would be run from cron.

The Solution

After a bit of messing around I came up with something better. It didn't need the database or cron and it was one line:

$active = round(time() / PLAYLIST_ROTATE_PERIOD) % count($playlists);

Why It Works

Dividing the current unixtime by the amount of time you want each playlist to be active for leads to a grouping of time chunks. Say you want each playlist to run for 3 hours (10800 seconds): round(1179685800 / 10800) = 109230.
Now 15 minutes later: round(1179686700 / 10800) = 109230. Same result.
Now 3 hours later: round(1179696600 / 10800) = 102931. The result increases one, which when modded by the number of playlists gives you the id of the next one in the list.