A Few Tips On How To Optimize Your CakePHP Website

What CakePHP offers is functionality. This is the main reason why developers use it, but the simple capability of creating web sites quicker than the regular solutions mean that optimization and loading times of the web site will suffer unless while expanding the developer skills you don’t keep up the trend and learn many techniques to optimize the web site whether you want more quality or more performance out of it.

The main objectives of this article are to learn about techniques to speed up load time, optimize the queries but also speed up cache query results.

Depending on each web site and elements, these objectives may pose big problems or quick solutions because there are simply too many parameters that count in this struggle for developing quality performance web sites.

One thing is certain: after reading this you will be able to understand how optimization techniques work and use them on your website.

Disable Debug Mode

The first thing to do in this quest for power is to turn off debugging. The default setting for Debug Mode is 2 and that is great for on going development but when the site is ready for launch it will only make you life harder so turning it to 0 is a good idea.

This is done by going to app\config\core.php and modifying the debug value to 0

1
2
3
<?php
  Configure::write(`debug`, 0);
?>

After doing that, CakePHP will cache elements of your design and thus decreasing loading time; once the elements are cached, it will not check each structure defined in the model. This is a very simple and efficient way to speed your CakePHP site.

Using recursive queries settings

By changing the way CakePHP joins or not the tables queried when using the bakery you can also speed up behavior this time.

If you want to query models and create numerous join statements the “0″ setting in the $this->Model->recursive = 0; is perfect. Example: It will return all the user data presuming that there are numerous photo albums and they are all tied to the users but it will also slow down all behavior and that is not always wanted.

However, if you want to reduce the number of ties between these albums, if we are to follow the example, and thus speed up the process, you can set -1 as a parameter and so do exactly what you desire:

1
2
3
<?php
  $this->Model->recursive = -1;
?>

Limiting requestAction();

A problem that is probably making lots of web developers curse daily is the requestAction issue that everyone wants to avoid but little know how. Basically what this does is that enables you to call other functions inside another view. This thing reduces considerably the amount of code that you have to rewrite just with several parameters changed but whenever you use it CakePHP adds a lot of data in the overhead as each request needs its own.

What many do is place in an element the views HTML code that needs using the requestAction() call. But this means that you have to load other elements from the two views and that means less time running but more time writing.

Query results caching

What many don’t know is that CakePHP requires processing queries and parsing the results in building a good sum of data arrays. But that is a lot of processing to do every time you search something and this can be avoided by caching the results in the caching system that CakePHP features.

What I will show you will, in most cases, speed up that process but I must warn you that if you cache incorrectly, the outcome will most surely be less pleasant and from that point on you might better start over again rather than finding the errors and correcting them.

Below I will provide the necessary steps in order to cache with the built-in caching system that CakePHP offers.

First you must create an application model (AppModel – if you don’t already have one) which should be located in the root folder of your app.

The below code example contains a find() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
  class AppModel extends Model {
    function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
      $doQuery = true;
 
      //check if we want the cache
      if (!empty($fields['cache'])) {
        $cacheConfig = null;
 
        //check if we have specified a custom config, e.g. different expiry time
        if (!empty($fields['cacheConfig'])) {
          $cacheConfig = $fields['cacheConfig'];
        }
 
        $cacheName = $this->name . '-' . $fields['cache'];
 
        //if so, check if the cache exists
        if (($data = Cache::read($cacheName, $cacheConfig)) === false) {
          $data = parent::find($conditions, $fields, $order, $recursive);
          Cache::write($cacheName, $data, $cacheConfig);
        }
 
        $doQuery = false;
      }
 
      if ($doQuery) {
        $data = parent::find($conditions, $fields, $order, $recursive);
      }
 
      return $data;
    }
  }
?>

This example enables the override the default find() function and searches for a string “cache” which is the new key that you implement. Once this found, the “generation” of the cache name is required, in this case Name-cacheName. The model name must be annotated as well in order to eliminate the eventual twice use of the name which would end up in an error.

Then it searches for another key that if it exist, it can let you set a timeout for the cached data. The name here is cacheConfig, which in the default CakePHP is about a week or so. However this is not that important as you will most probably set your own period of time.

Reading the cache with that name is done and if the cache is not present, you run an automatic query and save the results cached so that it will be present next time.

Now everything is set up for use but you need to do one more thing before actually using it. Let’s say that the table that you’re querying contains a list of countries. Now, this table is not going to be updated too often so you can cache the results successfully for easy find.

Let’s presume that the “Country” model and “Countries” controller have already been created.

1
2
3
4
5
6
7
8
9
10
<?php
  //get country list using default config
  $countries = $this->Country->find('list', array(
    'cache' => 'countryList'));
 
  //get country list using a custom config
  $countries = $this->Country->find('list', array(
    'cache' => 'countryList',
    'cacheConfig' => 'long'));
?>

The code above allows a find statement that once ran for the first time, CakePHP parses the results and stores the data retrieved in the cache but next time the query will be accessed the cached data will be opened and so no other search will be attended.

In order for the code above yo work you also need to add to your core.php file some lines of code:

1
2
3
4
5
6
7
<?php
  Cache::config('long', array(
    'engine' => 'File',
    'duration'=> '+1 months',
    'probability'=> 100,
    'path' => CACHE . 'long' . DS));
?>

Another thing to do is create a folder named “long” in the “tmp/cache” folder.

For example you have a country_controller.php file that enables the administrator to do anything he may need to do to it including adding or deleting and you may want to update the cached queries; the following code allows you to understand and do just that, if it is added to any function such as add, edit or delete.

1
2
3
4
<?php
  //we need to remove the status cache now
  Cache::delete('Country-countryList');
?>

This is all that can be done in this matter but if working with names and users you should place the name of the desired used in the cached key or you will get awkward results when opening the cached results.

Conclusion

If you can do these you can optimize your CakePHP website but you have to make sure that any other lame issues such as too many database queries, too many CSS files and others like these ones are solved.



 
 
 
Leave a comment
* Required.
* Required. Not published.
If you have one.

 

What we do

We do web programming and we do it at its best:
  • Websites based on MVC platform
  • Wordpress plugins and templates
  • Drupal modules and themes

Facebook for Business Purposes

 

Facebook has long ended in being just a social networking website and nobody could have predicted that it will be used as a powerful marketing tool. The fact that boosted the evolution of this socializing platform into such a powerful instrument is that nowadays it is available on any device that has a basic modern […]