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:

php
  1.   class PluralHelper extends Helper {
  2.     function ize($s, $c) {
  3.       if ($c != 1) {
  4.         return $c . ' ' . Inflector::pluralize($s);
  5.       }
  6.       return $c . ' ' . $s;
  7.     }
  8.   }

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:

php
  1. echo $plural->ize('article', count($articles));

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