|
| 1 | +.. index:: |
| 2 | + single: Inflector |
| 3 | + single: Components; Inflector |
| 4 | + |
| 5 | +The Inflector Component |
| 6 | +======================= |
| 7 | + |
| 8 | + The Inflector component converts English words between their singular and |
| 9 | + plural forms. |
| 10 | + |
| 11 | +Installation |
| 12 | +------------ |
| 13 | + |
| 14 | +.. code-block:: terminal |
| 15 | +
|
| 16 | + $ composer require symfony/inflector |
| 17 | +
|
| 18 | +.. include:: /components/require_autoload.rst.inc |
| 19 | + |
| 20 | +When you May Need an Inflector |
| 21 | +------------------------------ |
| 22 | + |
| 23 | +In some scenarios such as code generation and code introspection, it's usually |
| 24 | +required to convert words from/to singular/plural. For example, if you need to |
| 25 | +know which property is associated with an *adder* method, you must convert from |
| 26 | +plural to singular (``addStories()`` method -> ``$story`` property). |
| 27 | + |
| 28 | +Although most human languages define simple pluralization rules, they also |
| 29 | +define lots of exceptions. For example, the general rule in English is to add an |
| 30 | +``s`` at the end of the word (``book`` -> ``books``) but there are lots of |
| 31 | +exceptions even for common words (``woman`` -> ``women``, ``life`` -> ``lives``, |
| 32 | +``news`` -> ``news``, ``radius`` -> ``radii``, etc.) |
| 33 | + |
| 34 | +This component abstracts all those pluralization rules so you can convert |
| 35 | +from/to singular/plural with confidence. However, due to the complexity of the |
| 36 | +human languages, this component only provides support for the English language. |
| 37 | + |
| 38 | +Usage |
| 39 | +----- |
| 40 | + |
| 41 | +The Inflector component provides two static methods to convert from/to |
| 42 | +singular/plural:: |
| 43 | + |
| 44 | + use Symfony\Component\Inflector\Inflector; |
| 45 | + |
| 46 | + Inflector::singularize('alumni'); // 'alumnus' |
| 47 | + Inflector::singularize('knives'); // 'knife' |
| 48 | + Inflector::singularize('mice'); // 'mouse' |
| 49 | + |
| 50 | + Inflector::pluralize('grandchild'); // 'grandchildren' |
| 51 | + Inflector::pluralize('news'); // 'news' |
| 52 | + Inflector::pluralize('bacterium'); // 'bacteria' |
| 53 | + |
| 54 | +Sometimes it's not possible to determine a unique singular/plural form for the |
| 55 | +given word. In those cases, the methods return an array with all the possible |
| 56 | +forms:: |
| 57 | + |
| 58 | + use Symfony\Component\Inflector\Inflector; |
| 59 | + |
| 60 | + Inflector::singularize('indices'); // ['index', 'indix', 'indice'] |
| 61 | + Inflector::singularize('leaves'); // ['leaf', 'leave', 'leaff'] |
| 62 | + |
| 63 | + Inflector::pluralize('matrix'); // ['matricies', 'matrixes'] |
| 64 | + Inflector::pluralize('person'); // ['persons', 'people'] |
0 commit comments