Contact Us

Dessert #2 - Become friends with the Inflector

Posted on 14/9/06 by Felix Geisendörfer

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:


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:

<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


You can skip to the end and add a comment.

Nate said 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).

Felix Geisendörfer said 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.

This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.