Home/PHP Caching

PHP Caching

Published On: 10 June 2016.By .
  • Product & platform Engineering

PHP caching is good way to speed up the web page. By storing relatively static data in cache and serving it from cache when requested, the application saves the time that would be required to generate the data from scratch every time.

Caching can occur at different levels and places in a Web application. On the server side, at the lower level, cache may be used to store basic data, such as a list of most recent article information fetched from database; and at the higher level, cache may be used to store fragments or whole of Web pages, such as the rendering result of the most recent articles. On the client side, HTTP caching may be used to keep most recently visited page content in the browser cache.

download (1)

APC or Alternative PHP Cache, is a free open-source opcode (operation code) caching plugin for PHP. With APC caching your PHP script executions can run more efficiently, by cutting down on dynamic PHP executions.

You can simply install and enable it.

sudo apt-get install php-apc

After that you need to enable in php.ini file as apc.enable_cli = 1

Data caching is about storing some PHP variables in cache and retrieving it later from cache. It is also the foundation for more advanced caching features, such as query caching and page caching.

Core PHP example and steps.

1. Download the file Cache Master.php and copy in your project folder.
2. Create the instance of CacheMaster in your global config file.
    $cache = new CacheMaster();

    You can also define cache expire time
    $cache->expiryInterval = 3600; //no of seconds

3. Now you can write data in cache and next time you can read directly from cache.
      //try retrieving $data from cache 
   $data = $cache->get($key); 
   if ($data === false) { 
       $cache->put($key, $data); 
   } 
   //$data is available here
4. You can delete the cache by same key.
     $cache->remove_cache($key);

Yii2 Framework example:-
Yii2 framework have inbuilt classes to use caching. You can also manage cache provide like File, APC , MemCache etc.

 Steps:
     1. To access cache components : Yii::$app->cache.

     2. Yii2 configuration needs to add in common/config/main.php file.
    'components' => [
        'cache' => [
             'class' => 'yii\caching\ApcCache', // can be ApcCache, FileCache, MemCache
        ],
    ],
   3. Read / Write Data in cache
      if(Yii::$app->cache->get($key) == false){
         $data = Yii::$app->cache->get($key);
      }
      else{
          Yii::$app->cache->set($key, $data);         
      }
   4. Remove data from cache
         Yii::$app->cache->remove($key); 
   5. Cache Expiration can be set easily.
        // keep the data in cache for at most 45 seconds    
        $cache->set($key, $data, 45);

        sleep(50);

        $data = $cache->get($key);
        if ($data === false) {
            // $data is expired or is not found in the cache
        }
    6. Clear cache with some dependency

       // Create a dependency on the modification time of file example.txt.
       $dependency = new \yii\caching\FileDependency(['fileName' => 'example.txt']);

       // The data will expire in 30 seconds.
       // It may also be invalidated earlier if example.txt is modified.
       $cache->set($key, $data, 30, $dependency);

       // The cache will check if the data has expired.
       // It will also check if the associated dependency was changed.
       // It will return false if any of these conditions is met.
       $data = $cache->get($key);

You can found more details in the link http://www.yiiframework.com/doc-2.0/guide-caching-overview.html

HTTP Caching: You can install 2 php module and add some code to .htaccess file. This can be applied in every php project.

sudo apt-get install a2enmod headers
  sudo apt-get install a2enmod expires

You can disable these module if not required
sudo apt-get install a2dismod headers
sudo apt-get install a2dismod expires

<ifModule mod_headers.c>
    <FilesMatch "\.(ico|gif|jpg|jpeg|png|flv|pdf|woff)$">
       Header set Cache-Control "max-age=29030400"
    </FilesMatch>
    
    <FilesMatch "\.(js|css|swf)$">
       Header set Cache-Control "max-age=604800"
    </FilesMatch>
    
    <FilesMatch "\.(html|htm|txt)$">
       Header set Cache-Control "max-age=2700"
    </FilesMatch>
</ifModule>

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access 1 year"
    ExpiresByType image/jpeg "access 1 year"
    ExpiresByType image/gif "access 1 year"
    ExpiresByType image/png "access 1 year"
    ExpiresByType text/css "access 1 month"
    ExpiresByType application/pdf "access 1 month"
    ExpiresByType application/x-javascript "access 1 month"
    ExpiresByType application/x-shockwave-flash "access 1 month"
    ExpiresByType image/x-icon "access 1 year"
    ExpiresDefault "access 2 days"
</IfModule>

Note:
Query caching does not work with query results that contain resource handlers. For example, when using the BLOB column type in some DBMS, the query result will return a resource handler for the column data.
Some caching storage has size limitation. For example, memcache limits the maximum size of each entry to be 1MB. Therefore, if the size of a query result exceeds this limit, the caching will fail.

Download – Cache Master (1)

Related content

We Love Conversations

Say Hello
Go to Top