Friday 18 October 2013

php cache using APC cache in php and simple program to count pages views using apc cache


First of all we need to understand what is cache ?Cache is collection of items (data) stored in RAM . It is easily accessible . it does not require any I/O operation so its fast also .We use cache to optimize our application response time .

Cache in PHP :-

There are many ways we can use cache in php :-

      1)     Memcahce
       2)    APC


Here I will explain how to use APC .

APC is alternate php cache 

It is an extension to php . we can install it by following command .

             yum install pcre-devel
             yum install apc

Here are some predefined functions we need to use for APC .We can understand many functionalities just by name of the method .

apc_store () -- to store data in cache
apc_fetch() -- to fetch data from cache
apc_delete() -- to delete entries from cache
apc_inc() -- to increase integer value of any cache entry
apc_dec() -- to decrease integer value of any cache entry

Uses of functions :-

     apc_store('name','parveen');          //this will store name=’parveen ‘ in cache .
     apc_store('name','parveen',500);    // store in cache for 500 seconds.after that will be auto deleted 
     echo apc_fetch('name');                 // it will return ’parveen’
     apc_delete('name') ;                       // will delete from cache . if we try to fetch now then it will give error

example :-

apc_store('num',1);
apc_inc('num'); // now num is 2
apc_inc('num',5); //now num is 7
apc_dec('num'); // now num is 6
apc_dec('num',3); //now num is 3



Some points that we need to take care of :-

  1)  If memory of cache is full then it will delete all cache . so increase max limit size acording to your use . this can be achieved by making some entries in php.ini (php conf file)

   2) For better optimization we should set maximum time limit of cache . so that old entries get deleted automatically and free acquired space .


we can write following lines in php.ini file 

apc.shm_size="128M"       // this will set maximum size of cache to 128MB . default is 32 mb
apc.ttl="1800"                   // this will set maximum time to live for cache entry . default is unlimited


Simple page visits counter programs using cache :-

$key = 'visit_num';
if(apc_exists($key))
{
apc_inc($key, 1);

}
else
{
$count=1;
apc_store($key, $count);

}

and on hourly basis we can get that count from cache and store it in db . we can do it on daily basis or according to our convenience .

No comments:

Post a Comment