5 Common Mistakes Done by every Cakephp Developer!

Mistake 1: Improper Use of Containable Behaviours and Recursive Levels in ORM

On the discussion with a database developer about CakePHP, he told me that, with Object-relational mapping (ORM) it is easily accessible for SQL queries to become unnecessarily large.

How It Happens?

The CakePHP by default, selects the data automatically which may include, ‘Belongs To’, ‘Has One’ and ‘Has Many’ data, and this by default selection can lead to very large SQL queries. The SQL queries which takes place, are may not be a concern when you are originally developing an application. But, you may find that after six months the applications has become slow. And in some cases, applications may get crashed, if the queries aren’t optimized.

Solution:

When I was auditing an existing website, I find out two things as a solution. Read on-
Firstly, look for the recursive level that it has been changed or not?
The CakePHP always set the recursive level to 1 by default. I think it’s too high!
So like I do, set the recursive level to -1, and then make a use of containable behaviour to get any related models.
Second thing which I found is, has the Containable behaviour been used?
Most of the times, i get the client’s visit with an issue of slow CakePHP.

What Is The Reason Behind?

The reason is nothing serious, but again; no use of “Containable”. It’s well known that a professional developer of CakePHP, will always prefer to optimize their SQL queries regardless of how much “auto-magic” is done behind the display.

Therefore, be sure to make proper use of containable, as it has been founded the most effective way to optimize your SQL.

Mistake 2: Keeping Business Logic in Controllers, Rather than Models

Always be familiar that, Good CakePHP code will have somewhat real logic in the model files. If you make proper use of logical code in the model files, there will be no issue. Make sure that a controller file is used, for what it is sectioned in the MVC pattern. So use your controller file to have control on user actions, while allowing the business logic go in the model file.

Look for this example! It is a simple CRUD – a daily process! Let’s take the add posts function from a blog tutorial as an example. The default adds function is coded as follows:

public function add() {
if ($this->request->is('post')) {
$this->Post->create();
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your post.'));
}
}

If I talk about a simple add, then it is definitely fine! But, what would happen if you wish to perform the things like: “Send an email to the admin when a post was added”, or “Update another model association when a post was added”. This is additional logic, but don’t follow this logc into our controller file.

You may look forward with this function in our Post.php model. Maybe something like this:

public function addPost($data = array(), $emailAdmin = true) {
$this->create();
$this->save($data);
// update any other tables
// send the email to the admin user
if ($emailAdmin) {
}
// if all is successful
return true;
}

As a result, this would be the small changed to the controller action-

public function add() {
if ($this->request->is('post')) {
if ($this->Post->addPost($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your post.'));
}
}

Now you can notice here! The new action is actually one less line, because the $this->Post->create() has been moved to the model file.

Mistake 3: Adding Too Much Complexity to the Code, Instead of Returning Often and Early

This is the common mistake done by the CakePHP developer. In this, always a bit of an on-going debate, but returning often, and returning early absolutely bring out a clear looking code. This thing involves in the model methods much more.

But, what I want to tell you exactly, can be cleared through the method we added in the CakePHP tutorial above:

public function addPost($data = array(), $emailAdmin = true) {
$this->create();
$this->save($data);
// update any other tables
// send the email to the admin user
if ($emailAdmin) {
}
// if all is successful
return true;
}

What does, “To return often”, and “return early means”?

It actually means that, as we run through our function, we always verify to bring a surety that everything being done is ok on daily basis! And if it isn’t work correctly, then we return false, or return a CakePHP error.

Check out this simplest example- There are two ways the above function could be written:

public function addPost($data = array(), $emailAdmin = true) {
if ($data) {
$this->create();
$result = $this->save($data);
if ($result) {
// update any other tables
// send the email to the admin user
if ($emailAdmin) {
// send the admin email
}
} else {
// problem saving the data
return false;
}
// if all is successful
return true;
} else {
// no data submitted
return false;
}
}

Now here you may have observed that, how the code quickly becomes unreadable? There are ifs and elses all over the place, and the function quickly becomes one big indentation.

For more clear indentation, see that how the function looks if it written with the return often, return early principle.

public function addPost($data = array(), $emailAdmin = true) {
if (!$data) {
// no data submitted
return false;
}
$this->create();
$result = $this->save($data);
if (!$result) {
// problem saving the data
return false;
}
// update any other tables
// send the email to the admin user
if ($emailAdmin) {
// send the admin email
}
// if all is successful
return true;

It is clear from the above example that, you can easily view the code which only has a single indentation and is much easier to read.

Therefore in such manner, a CakePHP programmer should write the code. If the programmer writes the code from left to right, top to bottom, rather than properly writing it into different blocks, it will become very confusing!

Mistake 4: Not Using the DRY Principle

The DRY is defined as “Don’t Repeat Yourself”, which means a philosophy that should be followed when coding in CakePHP. If there is a use of object-oriented code, than there should not be any excuse given for repeating the same block of code twice.

Follow these four CakePHP tips to ensure you don’t repeat yourself:

Always keep a motive to put logic in model files so you can share the logic in the easiest way.

If you are habitual of repeating views in your view files, try to generate the view code as an Element, or even a custom helper.

Do some configuration settings - The app/Config/bootstrap.php file is a great place to set-up a configuration. This will allow you to code the things like: application name and the main email address. There may a chance that your client asks you to update an email address in an application. This is the last thing you want to do, as you have to go through hundreds of files.

Therefore, advice yourself to repeat the code, because you are getting chance to repeat the code again, and it could be written better.

Mistake 5: Not Commenting the Code

The last mistake which I want to document is no comments to the code.

Firstly, doc blocking- A doc block means, a document to the method or an action. Well, it hardly takes a minute to record something about, what a function is performing? But, it makes such a huge variation in terms of readability of code.

CakePHP Doc Blocks should be written against the left margin of the page. See the example below:

/**
* Adds & saves a post as well as emails the admin to let them know the post has been added.
* Also performs some saving to another table
*
* @param array $data The post data
* @param bool $emailAdmin If set to true, will email the website admin
* @return bool Returns true if successful
*/
public function addPost($data = array(), $emailAdmin = true) {

You can find a difference now! It hardly takes a minute to write a doc block, and doing so will makes a huge difference in terms of durability of the code.

Same goes with in-line comments! Always consider to explain, “What your code is doing and why?” It will make easy for other developer to understand the code easily.

With detailed information on above mistakes, it is clear that CakePHP is an extensive, full-featured framework. According to me, it leads to a code base which is founded more consistent, readable and understandable!

Get In Touch

+91-8285138670
Plot No 768, 1st Floor,
Udyog Vihar Phase 5
Gurgaon - 122016 (HR.) INDIA

Connect with us