Dessert #2 - Become friends with the Inflector

Posted by Felix Geisendörfer, on Sep 14, 2006 - in PHP & CakePHP » Core & Hacking

It's still day one of my "10 Days of Free Dessert!" challenge, and here comes the 2nd post already (which doesn't count for tomorrow of course).

One of my favourite class in CakePHP is the Inflector. Whenever I work with file names it's very useful to convert them from lower_case_and_underscored into CamelCasedOnes. Doing this is very easy:

php
  1. Inflector::camelize('my_file_name');

This would return MyFileName (even so the php docs in the class say "camelCased" which would make you think camelBack is being used, but it's really not).

Or yet another nifty trick you can use if you got a lot of similar Views, is to replace your Model name in them with a small piece of Inflector logic so you don't have to go through all of them and replace "Post" with "Item" and so on:

php
  1. <h2>Create a new <?php echo Inflector::classify($this->name); ?></h2>

If your Controller is named Posts, this would output a 2nd level headline saying: "Create a new Post". Of course this only works if you stick with the convention of using pluralized Controller names and singularized Model ones, but you can see the advantage.

So if all of this sounds convenient to you, go ahead and checkout /cake/libs/inflector.php to find out about all the other great functions it contains!

--Felix Geisendörfer aka the_undefined

Print this Post | Digg This | Stumble It | Delicious

2 Comments

Nate on Sep 14, 2006:

Jonathan Snook also posted some ideas for more generalized usage of the Inflector (although he instantiates it in his code example, I don't know why people do that).

http://withcake.com/posts/view/auto_pluralize

Felix Geisendörfer on Sep 14, 2006:

Thanks for adding this link Nate. I consider my post here to be just another "Check out the Inflector class if you haven't done so before"-pointer ; ). Their are virtually tons of ways to use the inflector.