CakePHP Pluralize Helper
Posted by Tim Koschützki, on Nov 02, 2007 - in PHP & CakePHP » Views & Helpers
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:
-
class PluralHelper extends Helper {
-
function ize($s, $c) {
-
if($c==0 || $c > 1) {
-
$inflect = new Inflector();
-
return $c . ' ' . $inflect->pluralize($s);
-
} else{
-
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. :]
3 Comments
Nice - I like the $plural->ize construct :)
Cool! :)
I like $plural too



[...] 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 [...]