CakePHP Pluralize Helper
Posted on 2/11/07 by Tim Koschützki
Hey folks,
here is a small helper file for the CakePHP framework that will help you turn a subject into the pluralized form depending on a parameter. Here is the code:
function ize($s, $c) {
if ($c != 1) {
return $c . ' ' . Inflector::pluralize($s);
}
return $c . ' ' . $s;
}
}
Save the code into a file called "plural.php" and place it in app/views/helpers/. After you activated the helper in your controller(s), you can use it as follows in your views:
..which will output "article" if the second parameter is 1, or "articles" if it is 0 or > 1. This is neat to display text as in "You have writte SOME_NUM article(s) already". You get the idea. It uses Cake's Infelctor class, so that special cases like "baby/babies" are taken care of as well.
One note: If you have a CommonHelper already, it would be good to copy the code into a "pluralize" method in the CommonHelper instead. Why? Because as of now the PluralHelper only has this one method and there does not justify to be a class on its own. :]
You can skip to the end and add a comment.
Nice - I like the $plural->ize construct :)
Cool! :)
I like $plural too
As a suggestion, rather than instantiate the Inflector class each time the ize() method is called, have the inflector a class-level variable that is created as the Helper class is constructed. It saves on the overhead of continually creating and discarding the instance if you need to call ize() multiple times.
Richard: Inflector::getInstance() is a singleton setup, so there isn't much overhead in using it statically. Or do you mean something else?
@Tim Koschützki: the thing is, you are instantiating a new Inflector in every PluralHelper::ize() call and when it calls Inflector::pluralize it will get the singletone instance and using it's already loaded inflections, so instantiating a new Inflector() is totally useless and overheadable. You should just use the static method.
Oh right, the version of the code here is in fact old. I did not remember it when making the earlier comment, hence the comment.
Fixed it. Thanks for the heads up!
Also cleaned the function up a bit.
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.
[...] Koschuetzki has another CakePHP tip to share on his blog today - a helper that lets you pluralize a word easily. Here is a small helper file [...]