Understanding Inflector in Cakephp

| By Webner

Understanding the purpose and usage of Inflector in Cakephp

The Inflector class in cakephp is used to modify single/multi word strings into different formats using its build-in methods. We don’t need to use core php methods such as str_replace if you want to remove space/underscore between the words, convert string to CamelCase etc.

There are various methods of inflector class that are briefly described below.
Include – use Cake\Utility\Inflector at the top of the php file.

1. classify(): This method basically returns the standard form of the text.

$string = “people”;
Inflector ::classify($string);
Output:  Person

Similarly other examples are:

E.g.  $string = “Excel 2016 basic” or $string = “Excel_2016_basic”

Output: Excel2016Basic

2. camelize(): It converts the string to CamelCase.

 $string = “webner solutions”;
 Inflector ::camelize($string);
Output: WebnerSolutions

3. pluralize(): It converts the singular word to plural form.

 $string =  “Learn the basic”;
 Inflector ::pluralize($string);
Output: Learn the basics

4. singularize() : It returns the pluralize word into singular form.

 $string =  “Oranges”;
 Inflector ::singularize($string);
Output: Orange

5. underscore(): It converts the CamelCase String to underscore string.

 $string =  “LearnByDoing”;
 Inflector ::underscore($string);
Output: learn_by_doing

6. humanize(): It converts the lower case words with capitalized ones and replace underscore with spaces.

 $string = “this is not an easy_task.”;
 Inflector ::humanize($string);
Output: This Is Not An Easy Task

7. dasherize(): It converts CamelCased or underscored string to dashed string.

 $string = “printTitlesGridlinesAndHeadings“;
 Inflector ::dasherize($string);
Output: print-titles-gridlines-and-headings

8. variable(): It returns camelBacked version of the an underscored-string.

 $string = “Basic_style_string”;
 Inflector ::variable($string);
Output: basicStyleString

Leave a Reply

Your email address will not be published. Required fields are marked *