Using CRUD for organizing controller code

CakePHP is a great framework as it forces MVC design pattern on your web application, keeping your model, view, and controller code separated. However, as your application grows bigger, your controller class will get bigger and messier. There is no good suggested way for organizing functions within a controller class.

What I have realized this week is following the general CRUD database principle can help you a long way in keeping your controller class clean, bug-free and with minimum code duplication. After cleaning up many of my controller classes using the above approach, I finally ended up creating this PHP class template as a guide for all my future controller class related coding

Class extends AppController{
//***********************************************
// METHODS RELATED TO CREATE
//************************************************
function add(){…}
function __addReatedPrivateMethods{…}

//***********************************************
// METHODS RELATED TO UPDATE
//************************************************
function updateXXX(){…}
function __updateReatedPrivateMethods{…}

//***********************************************
// METHODS RELATED TO DELETE
//************************************************
function delete(){…}

//***********************************************
// METHODS RELATED TO READ/View
//************************************************
function index(){…}

}

Two things about the template
1. It is important to keep add and update methods one below the other as you will find many pieces of code that be used by both add and update functions
2. Functions related to read or “view” are often independent of the other three – Create, Update, and Delete – and thus can be place either at the beginning or at the end of the code
Let me know if you have any better ways of organizing controller cod

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s