Skip to main content

Why implement Fat Model and Skinny Controller in CakePHP

Fat Model and Skinny Controller encourages developers to include as much business logic into the application models and the controllers should translate the requests, instantiating classes, getting data from the domain objects and passing it to the view.
  • This development methodology is not new but rarely adopted among the developers. Developers should focus on creating model behaviors rather than creating controller components.
  • It is a simple and powerful concept to implement is offers numerous convenient features to the developers.
  • Controller is responsible for handling & executing the actions routed through the router, it should be lightweight and agile in nature.
  • It is not about counting the lines in controller, rather putting codes in the right place.
Why Fat Model and Skinny Controller:
After developing for a while, when you look back at your code you’ll realize how hard it is to keep track of all these things. When you have a Fat Controller, it can get pretty messy even with a proper formatting.
Put as much of your code that deals with data manipulation in your Model and it solve the problem.
  • When we need some actions repeatedly in different controller, we can have them in Model.
  • We can reduce the use of requestAction() in CakePHP sites with fat models.
  • It’s easier to find out what went wrong when your methods are smaller and specific. Because, model methods are more specific than controller methods.
How to use?
Code-you should put in Controllers
  1. Usually the only functions you should have in controllers are the view functions.
  2. “before” functions, Index, Login, Signup, Add, Edit, View, Delete.
Everything else can go to your model.
Code-you should put in Models


  1. You should put the code and functions in your model that relates to Model and its data.
  2. Formatting, Retrieving, Searching, Pagination are few examples.
  3. Keep all your business logic in the models (try to write generalized methods whenever possible). Call your generalized methods from controller by passing the required parameters.
  4. Using this you will end up writing self-documented code.
  5. It is absolutely fine if your view contains some PHP code which deals with the presentation logic.
  6. You can use the Model’s callback methods like: beforeFind, afterFind, beforeValidate, beforeSave, afterSave, beforeDelete, afterDelete, onError


Example with Sample Code
Below is the example of a listing page using CakePHP paginate, search, sorting with the concept of Fat Model and Skinny Controller.
Let’s get the User list,
  • In your Controller’s Action

$limit = 10;
$this->paginate = $this->User->_Pagination($limit,$_GET['search']);
//To write your business logic, lets call another Model method
$listdata = $this->User->formatListing($this->paginate('User'));
$this->set('listdata', $listdata);


  • In Your corresponding Model
public function _Pagination($limit = 30,$search){
$conditions = array('User.is_active'=>1);
if(isset($search) && trim($search)) {
$search = urldecode(trim($search));
$conditions['User.name LIKE'] = '%'.$search.'%';
}
$params = array(
'conditions' => $conditions,
'fields' => array('id','name','email','created'),
'limit' => $limit,
'order' => array('User.name'=>'asc','User.created' => 'desc'),
);
return $params;
}
public function formatListing($userList){
$listdata = array();
foreach($userList as $ukey=>$data) {
$listdata[$ukey]['id'] = $data['User']['id'];
$listdata[$ukey]['email'] = $data['User']['email'];
$listdata[$ukey]['name'] = $data['User']['name'];
$listdata[$ukey]['created'] = date('M d, Y',strtotime($data['User']['created']));
}
return $listdata;
}


Why FAT Model and why not Components?
  • Components should have the logic that can be shared across multiple controllers.
  • Logic should be placed inside the Components to get the data for the view. If the logic includes manipulating of the data, then it should be in a model.
Note these Check points while implementing above steps:
  • When you need to call controller methods inside a model then you are obviously doing something wrong and need to re-examine your code.
  • CakePHP will create an automatic model (instance of AppModel) when there is a table but no model file. When you create a model with wrong model file name, still CakePHP will access automodel. Hence, it results in different behaviors and all your validations and custom functions will not work.
Too much eating may cause gaining weight, once you’re overweight; it’s too hard to lose that extra weight.
If you don’t want to end up with overweight controllers which eventually will require surgical intervention, just follow the basics and that’s Fat Model and Skinny Controller

Comments

Popular posts from this blog

How to Create a PDF file in Cakephp 2.0 using Fpdf

Step 1: Download FPDF folder from  http://www.fpdf.org/  . Step 2: Unzip the downloaded Fpdf file and name it “fpdf” or however you require and make sure that you use the same name while calling it. Step 3: Move the “fpdf” unzipped files to  your /app/Vendor directory within Cakephp. Now you should have the directory path as   /app/Vendor/fpdf. Step 4: Create a new Cakephp layout file for the pdfs. We will use this layout when serving a pdf to the client. Create a file called pdf.ctp inside of /app/View/Layouts. Add the following code to /app/View/Layouts/pdf.ctp Layout: /app/View/Layouts/pdf.ctp 1 2 3 4 <?php      header ( 'Content-Disposition: attachment; filename="downloaded.pdf"' ) ;      echo $content_for_layout ; ?> The header function above tells the browser that it is going to receive a file called download.pdf. If you want to change the name

Setup CakePHP Using Xampp On Windows

Step 1: Download XAMPP  and  CakePHP .   Step 2: Install Xampp Once you have installed Xampp (version 1.7.3) on your Windows with the default option, all your files will be located in the C:\xampp folder. Step 3: Mod Rewrite Module Once Xampp is installed as the local server, you can then proceed to enable mod_rewrite. To do so, you will have to open the httpd.conf file that is located in C:\xampp\apache\conf and uncomment by removing # from the following line: # LoadModule rewrite_module modules/mod_rewrite.so Step 4: Place CakePHP Files in a New Folder Extract the CakePHP (version 1.3.8) zip file and copy all its contents to your local web server, which in this instance is C:\xampp\htdocs\cakephp . I have decided to name the CakePHP folder as cakephp, and in it, you will find many files and folders for the framework, including app, cake, docs, vendors, .htaccess, and index.php. Step 5: Set Up Virtual Host Open the httpd-vhosts.conf file from the C:\xampp\apa

Installing Wamp on Windows

WAMP is an abbreviated name for the software stack Windows, Apache, MySQL, PHP. It is  derived from LAMP which stands for Linux, Apache, MySQL, and PHP. As the name implies, while LAMP is used on Linux servers, WAMP is used on Windows servers.  The “A” in WAMP stands for Apache.  Apache  is server software that is used to serve webpages. Whenever someone types in your WordPress website’s URL, Apache is the software that “serves” your WordPress site. The “M” in WAMP stands for MySQL.  MySQL  is a database management system. It’s job in the software stack is to store all of your website’s content, user profiles, comments, etc. The “P” in WAMP stands for PHP. PHP is the programming language that WordPress is written in. It is also the piece that holds the entire software stack together. It runs as a process in Apache and communicates with the MySQL database to dynamically build your webpages. Download the wamp for the url  http://www.wampserver.com/en/download.php .  You

Dynamic Sitemap Generation plugin in Cakephp

Here for the SEO implementation we need to generate the sitemap.xml in our application which is accessed by the webmaster tool. So here i am outlined the steps to generate the Xml file . 1. Lets think we have controller by name sitemap,Inside that create an action by name sitemap and paste the following code    public function sitemap(){     $this->layout='ajax';     $this->RequestHandler->respondAs('xml');     $listData = $this->Sitemap->find('all',/*Conditions if you have any*/);     $this->set(compact('listData')); } I through variable $listData to render all data( Keywords,Title,Url,etc ...) that will be shown in sitemap.xml.  This   depends   on the   dynamic link  what   we want to   show  in sitemap.xml.For request handler to work include the RequestHandler component public $components = array('RequestHandler'); Step 2. Create View based on action sitemap On structure MVC as default we need create sitemap.