Susina Utils

How To

In this section you will find some examples of how to use the library.

How to use Doctrine Inflector with StringUtils

The StringUtils class uses SimpleInflector by default to pluralize/singularize strings. It's a very handy and thiny library but sometimes you could need something more featured and advanced, for example supporting multiple languages. In this case you can use the Doctrine Inflector class.

pluralize and singularize methods of StringUtils accept an optional second argument, which is an instance of a class implementing the InflectorInterface interface.

Doctrine Inflector class already exposes pluralize and singularize methods, but it does not implement the InflectorInterface interface, so we need to create an empty class implementing the interface and extending the Doctrine Inflector:

use Doctrine\Inflector\Inflector;
use Susina\Utils\Inflector\InflectorInterface;

class DoctrineInflector extends Inflector implements InflectorInterface
{
    // empty class, just to implement the interface
}

Now, we can use the DoctrineInflector class with StringUtils :

use Doctrine\Inflector\CachedWordInflector;
use Doctrine\Inflector\Rules\Italian;
use Doctrine\Inflector\RulesetInflector;
use Susina\Utils\StringUtils;

$inflector = new DoctrineInflector(
    new CachedWordInflector(new RulesetInflector(
        Italian\Rules::getSingularRuleset()
    )),
    new CachedWordInflector(new RulesetInflector(
        Italian\Rules::getPluralRuleset()
    ))
);

$word = 'susina';
$plural = StringUtils::pluralize($word, $inflector);

echo "Pluralize '$word' results in '$plural'.\n";
// Output: Pluralize 'susina' results in 'susine'.

Thanks to PHP Anonimous classes we can also write the previous example in a more compact way, without creating a new class:

use Doctrine\Inflector\CachedWordInflector;
use Doctrine\Inflector\Rules\Italian;
use Doctrine\Inflector\RulesetInflector;
use Susina\Utils\StringUtils;
use Susina\Utils\Inflector\InflectorInterface;

$inflector = new class(
    new CachedWordInflector(new RulesetInflector(Italian\Rules::getSingularRuleset())),
    new CachedWordInflector(new RulesetInflector(Italian\Rules::getPluralRuleset()))
) extends Inflector implements InflectorInterface {};

$word = 'susina';
$plural = StringUtils::pluralize($word, $inflector);

echo "Pluralize '$word' results in '$plural'.\n";
// Output: Pluralize 'susina' results in 'susine'.

Search results