logo

Easy Cakephp naming conventions

cakephp

CakePHP naming conventions can be found on CakePHP official website in detail, but here I will try to trim it to make it more easy to understand.

What are naming conventions

These are optional rules to name your database tables, Fields in a table, Files, Classes and Functions or Methods in classes, folder structure proposed etc.

What are Benefits of CakePHP naming conventions

If we follow CakePHP naming conventions we will get most of features automatically without writing code for it, If we do not follow naming conventions we will have to explicitly write code for many things. Like according to CakePHP naming convention the view file must name same as function name.
suppose we have index function, View file must name index.ctp
our function will look like

Above function will automatically render index.ctp file

Lets see what if we do not follow this convention
we have function named index, but view file named home.ctp
then we will have to explicitly define view as in below code.

Hence each convention has its own advantage and I do not think it has any disadvantages.

I will explain naming convention supposing post_comments database table.

Database tables

  • Table name must be plural
  • Table name must be lower cased
  • underscore should be used as name separator eg post_comments
  • id field should exist
  • foreign key field should be named as singular_parent_table_id eg user_id means if field in users table

Models

  • Model names should be singular
  • File name should be CamelCased eg PostComment.php
  • Class name should also be singular and CameCased
  • Model files should be placed in app/Model

Controllers

  • Controller names should be Plural
  • File name should be CamelCased with post-fix Controller eg PostCommentsController.php
  • Class name should also be Plural, CameCased and post-fixed
  • Controller files should be placed in app/Controller

As we have many functions in a controller like (index, view, edit, delete etc) which reflects in pages, So we will have a folder for each controller in app/View directory, in which we will be having .ctp files for each function of controller.

Views

  • Controller names should be Singular
  • File name should same as function nameeg index.ctp
  • Must be places in folder named same as controller name without post-fix eg for above scenario our controller name is PostCommentsController so our view folder should name as PostComments
  • View folder should be placed under app/View
  • eg app/View/PostComments/index.ctp
    app/View/PostComments/view.ctp
    app/View/PostComments/edit.ctp
  • We do not need view file for delete function.
NOTE: In CakePHP the functions or methods are referred as Actions.

Comments

    Write a Reply or Comment

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