Why Implement Fat Model And Skinny Controller in CakePHP

Fat Model and Skinny Controller in CakePHP framework 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

Skinny_Controller_logic

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

[sourcecode]$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);[/sourcecode]

  • In Your corresponding Model

[sourcecode]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;

}[/sourcecode]

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 auto-model. 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

CakePHP_fat_models

 

Suggest me if I am somewhere wrong. Any suggestions are welcome.

Beginner’s Guide to Cropping Images in PHP Using ImageMagick

While using images in a web application, developers can’t always include images of a particular measurement. In such cases, resizing the images for the application would be a good option but, not efficient either. For example, resizing a long vertical image into a horizontal dimension would just squeeze the image; thereby, affecting the aesthetics of the website and also reducing the purpose of it. Hence it would be smart to implement a cropping tool like ‘ImageMagick’ in order to fit images of various dimensions into a specified size.

ImageMagick is a collection of robust and convenient tools for manipulating images. It can be used to crop images of numerous formats such as JPEG, PNG, GIF, TIFF, PhotoCD and many more. ImageMagick facilitates creation of dynamic images that are fitting to the specific requirements of web applications.

Difference Between Cropping in GD Library and ImageMagic:

GD is the most commonly used extension for PHP. It is popular because it is easier to install and configure (`yum install php-gd` on Fedora, CentOS etc or `sudo apt-get php5-gd` on ubuntu). However, it has some limitations such as:

  • It is comparatively slower
  • It is more memory intensive
  • For certain aspects it can be more complex to use.

Below I have mentioned a sample code for image cropping using GD:

[sourcecode]<?php
function resize_my_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newGDwidth = $w;
$newGDheight = $h;
} else {
if ($w/$h > $r) {
$newGDwidth = $h*$r;
$newGDheight = $h;
} else {
$newGDheight = $w/$r;
$newGDwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newGDwidth, $newGDheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newGDwidth, $newGDheight, $width, $height);

return $dst;
}

$img = resize_my_image(‘/path/to/some/image.jpg’, 150, 150);
?>[/sourcecode]

You can either output it to the browser or save it to a file using the ‘imagejpeg’ function.

Imagick:

Imagick is a less frequently used PECL extension. ImageMagick is a free tool that is used for creating and manipulating images that supports over 100 different image formats. This can be used on a command line tool for any programming language. The Imagick extension essentially provides an API for all of the functionalities available in the `convert` command line tool.

Some of its advantages are:

  • It is faster
  • It uses less memory
  • Offers more powerful functionality
  • Imagick’ is lot easier to use (once you figure out how), your code may end up smaller and cleaner.

The down side of using this extension is that the documentation is extremely limited and there are almost no examples available on the web. Installation on the other hand can be a painful task as well.

Although it should just be a matter of running the command `pecl install imagick`.

Sample code:

Cropping larger images:

Put a big picture named andolasoft_logo.jpg along side with your php page, run the test and check the directory to see andolasoft_logo_thumb.jpg.

Requirement:

imagemagick with imagick extension

[sourcecode]<?php
$obj = new imagick(‘andolasoft_logo.jpg’);
//resize the above image
$obj->thumbnailImage(160, 0);
//write the thumb
$obj->writeImage(‘andolasoft_logo_thumb.jpg’);
?>[/sourcecode]

To Crop Animated Image:

[sourcecode]<?php
$image = new imagick(“andolasoft_animated_logo.gif”);
$image = $image->coalesceImages(); // the trick! To crop animated image
foreach ($image as $frame) {
$frame->cropImage($width, $height, $x, $y);
$frame->setImagePage(0, 0, 0, 0); // Remove gif canvas
}
?>[/sourcecode]

$x → The X coordinate of the cropped region’s top left corner
$y → The Y coordinate of the cropped region’s top left corner

Implementing ‘ImageMagick’ would make the website look clean and flawless. Images on the other hand retain its look and feel, thereby making the application look professional and optimized.

Find anything amiss here, then share it with us.

CakePHP is Faster Development Of Next Generation Web Application

There are numerous PHP frameworks available such as Zend, CodeIgniter, Akelos etc. CakePHP on the other hand is the most popular framework among them and reduces significant coding time and investment. It is an open source web application development tool. It helps to build the web pages and applications faster and simpler.

Some features of CakePHP framework

  • Compatible with almost all PHP versions
  • Facilitates code scaffolding for faster development of prototypes
  • Doesn’t require any complex configuration
  • This framework is safe and secure:  It provides in-built tools for input validation, XSS prevention, SQL prevention for secure application development.
  • It provides built-in view helpers for AJAX, JavaScript, HTML etc.
  • It offers faster and flexible tempting features as well as data validation features

Never miss an update from us. Join 10,000+ marketers and leaders.

These features make installation and use of CakePHP easy which in turn makes PHP more manageable. As it is an open source, it can be customized according to the needs of specific business requirements. It provides the CakePHP developers with MVC framework, Class inheritance, re-usability, Ajax support and many more to make the development process easier and effortless.  It assists the PHP developers at all levels and provide the ability to manage every part of project development.

Conclusion

It has a lot of advantages over other PHP frameworks, such as less code, less maintenance, and more scalability. CakePHP team works tirelessly to make sure that programmers who want to use CakePHP can do so in an easy and enjoyable way. CakePHP itself is easy to use, and the framework has many features to make life easier for developers who need to create applications that work well and scale to large numbers of users.

Our CakePHP development team is highly experienced to deliver robust, logical, most reliable and effective solutions to our global clients. Our expertise in CakePHP development helps us for building cost effective apps that too matching customer budget with quick turn-around time.

The Ultimate Guide To Facebook Login Migration Using PHP SDK (v3.0.0)

Facebook is the world’s largest social network with more than 2 billion monthly active users. There are so many users because it is a convenient way for people to connect with friends. The login process is smooth and simple, which makes it very easy for users to sign up and log in.

That’s why different websites such as blogs, news outlets, businesses, organizations, etc. have been integrating Facebook Login into their website by using Facebook Login API. There are more than 500 million people who log into their apps or websites using the same credentials they use on Facebook. It just makes things easier for them and more importantly, it helps businesses build trust among their users by giving them the option to sign in via their existing Facebook account.

Never miss an update from us. Join 10,000+ marketers and leaders.

If you are doing a migration from v2.2.x to v3.0.0

You Need To Do the Following Changes.

  • Download SDK: https://github.com/facebook/facebook-php-sdk
  • Keep the two classes base_facebook.php and facebook.php with the certificate fb_ca_chain_bundle.crt
  • Include facebook.php in your PHP file.
  • If you’re currently using the PHP SDK (v2.2.x) for authentication, you will recall that the login code looked like this:
include_once("facebook.php"); OR include_once("base_facebook.php");
$facebook = new Facebook(…);
$session = $facebook->getSession();
if ($session) {
// proceed knowing you have a valid user session
} else {
// proceed knowing you require user login and/or authentication
}
  • The login code is now:
include_once("facebook.php");
$facebook = new Facebook(…);
$user = $facebook->getUser();
if ($user) {
// proceed knowing you have a logged in user who's authenticated
} else {
// proceed knowing you require user login and/or authentication
}

I hope you like this post and if you want to get such type of updates then please subscribe to our email. You can also visit our PHP/CakePHP portfolio page to see all our apps developed on PHP or CakePHP platform.

Why CakePHP is Popular? And The Role Of CakePHP Developer

CakePHP is an open source PHP based rapid development framework. It offers great run-time infrastructure along with abundant set of libraries for CakePHP developers. Cake PHP development is supported by the MVC (Model View and Controller) architecture which differentiates the programming logic from the data presentation layer.

It also features other programming concepts like Front Controller, Association Data Mapping and Active Record. Along with these, there are numerous other features that make CakePHP one of the most preferred web development frameworks among others.

Let’s take a look at some features here

Wide Community:

CakePHP developers are supported by huge peers who make use of this framework. There are many contributors and programmers who share the community. For this reason, using the framework is simpler for development as well as for research.

Never miss an update from us. Join 10,000+ marketers and leaders.

Reusability:

It facilitates the developers in saving a lot of efforts through PHP development. Because the programmer make use of a pre-written code for more than one project. In other words, they can focus on the logical and creative part of application whereas the tedious task of coding could be handled with ease.

Open Source:

The framework is open source, for which the CakePHP developers do not have to spend any amount in the process of development and have complete access to its source code. It also assists the developers in adding robustness and improves performance in web applications.

Some of the roles of CakePHP developers include

    • Manage development efforts and framework efficiently
    • Support product releases
    • Ability to handle lot of projects in less time
    • Overall review of the quality & progress of the work
    • Support stable user growth

Conclusion

Here at Andolasoft we provide our customers with a unique and up-to-date approach towards their Web-app development. We design and develop intriguing web applications using PHP/CakePHP. We follow agile development approach to deliver project on time and within budget to our customer