debuggable

 
Contact Us
 

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:

  class PluralHelper extends Helper {
    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:

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

 
&nsbp;

You can skip to the end and add a comment.

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

Tarique Sani said on Nov 06, 2007:

Nice - I like the $plural->ize construct :)

PHP Encoder said on Feb 19, 2008:

Cool! :)
I like $plural too

Richard said on Sep 29, 2008:

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.

Tim Koschützki said on Sep 29, 2008:

Richard: Inflector::getInstance() is a singleton setup, so there isn't much overhead in using it statically. Or do you mean something else?

rafaelbandeira3 said on Sep 29, 2008:

@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.

Tim Koschützki said on Sep 30, 2008:

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!

Tim Koschützki said on Sep 30, 2008:

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.