CakePHP Conventions

We are big fans of convention over configuration. While it takes a bit of timeto learn CakePHP’s conventions, you save time in the long run. By followingconventions, you get free functionality, and you liberate yourself from themaintenance nightmare of tracking config files. Conventions also make for a veryuniform development experience, allowing other developers to jump in and help.

Controller Conventions

Controller class names are plural, PascalCased, and end in Controller.UsersController and ArticleCategoriesController are both examples ofconventional controller names.

Public methods on Controllers are often exposed as ‘actions’ accessible througha web browser. For example the /users/view maps to the view() methodof the UsersController out of the box. Protected or private methodscannot be accessed with routing.

URL Considerations for Controller Names

As you’ve just seen, single word controllers map to a simple lower case URLpath. For example, UsersController (which would be defined in the file nameUsersController.php) is accessed from http://example.com/users.

While you can route multiple word controllers in any way you like, theconvention is that your URLs are lowercase and dashed using the DashedRouteclass, therefore /article-categories/view-all is the correct form to accessthe ArticleCategoriesController::viewAll() action.

When you create links using this->Html->link(), you can use the followingconventions for the url array:

  1. $this->Html->link('link-title', [
  2. 'prefix' => 'MyPrefix' // PascalCased
  3. 'plugin' => 'MyPlugin', // PascalCased
  4. 'controller' => 'ControllerName', // PascalCased
  5. 'action' => 'actionName' // camelBacked
  6. ]

For more information on CakePHP URLs and parameter handling, seeConnecting Routes.

File and Class Name Conventions

In general, filenames match the class names, and follow the PSR-4 standard forautoloading. The following are some examples of class names and their filenames:

  • The Controller class LatestArticlesController would be found in a filenamed LatestArticlesController.php
  • The Component class MyHandyComponent would be found in a file namedMyHandyComponent.php
  • The Table class OptionValuesTable would be found in a file namedOptionValuesTable.php.
  • The Entity class OptionValue would be found in a file namedOptionValue.php.
  • The Behavior class EspeciallyFunkableBehavior would be found in a filenamed EspeciallyFunkableBehavior.php
  • The View class SuperSimpleView would be found in a file namedSuperSimpleView.php
  • The Helper class BestEverHelper would be found in a file namedBestEverHelper.php

Each file would be located in the appropriate folder/namespace in your appfolder.

Database Conventions

Table names corresponding to CakePHP models are plural and underscored. Forexample users, article_categories, and user_favorite_pagesrespectively.

Field/Column names with two or more words are underscored: first_name.

Foreign keys in hasMany, belongsTo/hasOne relationships are recognized bydefault as the (singular) name of the related table followed by _id. So ifUsers hasMany Articles, the articles table will refer to the userstable via a user_id foreign key. For a table like article_categorieswhose name contains multiple words, the foreign key would bearticle_category_id.

Join tables, used in BelongsToMany relationships between models, should be namedafter the model tables they will join or the bake command won’t work, arranged inalphabetical order (articles_tags rather than tags_articles). If youneed to add additional columns on the junction table you should createa separate entity/table class for that table.

In addition to using an auto-incrementing integer as primary keys, you can alsouse UUID columns. CakePHP will create UUID values automatically using(Cake\Utility\Text::uuid()) whenever you save new records usingthe Table::save() method.

Model Conventions

Table class names are plural, PascalCased and end in Table. UsersTable,ArticleCategoriesTable, and UserFavoritePagesTable are all examples oftable class names matching the users, article_categories anduser_favorite_pages tables respectively.

Entity class names are singular PascalCased and have no suffix. User,ArticleCategory, and UserFavoritePage are all examples of entity namesmatching the users, article_categories and user_favorite_pagestables respectively.

View Conventions

View template files are named after the controller functions they display, in anunderscored form. The viewAll() function of the ArticlesController classwill look for a view template in templates/Articles/view_all.php.

The basic pattern istemplates/Controller/underscored_function_name.php.

Note

By default CakePHP uses English inflections. If you have databasetables/columns that use another language, you will need to add inflectionrules (from singular to plural and vice-versa). You can useCake\Utility\Inflector to define your custom inflectionrules. See the documentation about Inflector for moreinformation.

Plugins Conventions

It is useful to prefix a CakePHP plugin with “cakephp-” in the package name.This makes the name semantically related on the framework it depends on.

Do not use the CakePHP namespace (cakephp) as vendor name as this isreserved to CakePHP owned plugins. The convention is to use lowercase lettersand dashes as separator:

  1. // Bad
  2. cakephp/foo-bar
  3.  
  4. // Good
  5. your-name/cakephp-foo-bar

See awesome list recommendationsfor details.

Summarized

By naming the pieces of your application using CakePHP conventions, you gainfunctionality without the hassle and maintenance tethers of configuration.Here’s a final example that ties the conventions together:

  • Database table: “articles”
  • Table class: ArticlesTable, found at src/Model/Table/ArticlesTable.php
  • Entity class: Article, found at src/Model/Entity/Article.php
  • Controller class: ArticlesController, found atsrc/Controller/ArticlesController.php
  • View template, found at templates/Articles/index.php

Using these conventions, CakePHP knows that a request tohttp://example.com/articles maps to a call on the index() function of theArticlesController, where the Articles model is automatically available (andautomatically tied to the ‘articles’ table in the database), and renders to afile. None of these relationships have been configured by any means other thanby creating classes and files that you’d need to create anyway.

Now that you’ve been introduced to CakePHP’s fundamentals, you might try a runthrough the Content Management Tutorial to see how things fittogether.