Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does cakePHP naming convention work?

Tags:

cakephp

I'm relatively new to PHP. Started learning PHP, but then come across cakePHP, which is suppose to speed up development time.

After reading the documentation and blog tutorial I still don't understand the naming convention. I guess I won't know until I start to do some examples, but to get me started can someone please explain to me how cakePHP associate database tables to the controller/model layer?

The below code is an abstract from the tutorial. It is a controller method that passes the post id to the view layer. The database table is called "posts". $this->Post refers to the model class of Post, which correlates to the plural form of posts in the database.

public function view($id = null) {
  $this->Post->id = $id;
  $this->set('post', $this->Post->read());
}

OK I get that. Then, in the documentation it refers to the following correlation:

ReallyBigPerson and really_big_people

So it seems like the correlation actually follows the rule in English semantics. Does this mean that cakePHP has a list of singular and plural words hidden somewhere that it works from? For example can I use the below correlation without breaking the code?

This and these or Man and men or Foot and feet or Moose and moose or Goose and geese

Furthermore, if I have both singular and plural form of tables in my database, will it break the code, or will it just associate to the plural-formed table?

Just find it baffling... Why couldn't they just match the naming convention like for like with prefixes?

like image 622
chaser Avatar asked Aug 09 '12 02:08

chaser


1 Answers

Inflector

CakePHP uses its Inflector class to determine the plurals of things.

Since the naming conventions dictate that model names are singular and tables names are pluralised, it uses the inflector to apply English semantics / rules to determine the plural.

If you need some help understanding the output of the Inflector, you can use the CakePHP inflector website.

Pluralisation Examples

Model name: Post
Table name: posts

Model name: User
Table name: users

Model name: Sheep
Table name: sheep

Model name: News
Table name: news

Model name: Radius
Table name: radii

Check the Inflector site to be sure.

Non-standard Table names

While CakePHP offers a standard rule set for naming and conventions, none of it is set in stone. If you want to change the name of the table used for a particular model, simply specify the table name in the model:

class Thing extends AppModel {
    public $useTable = 'somethings';
}

Or, if you want a model that does not use a table:

class Post extends AppModel {
    public $useTable = null;
}
like image 172
Predominant Avatar answered Oct 16 '22 19:10

Predominant