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

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


Incoming Links (via Tecnorati):
Nothing Reported

Tags: .NET, CakePHP, Code, PHP, Text Transformation