Submit Your Site For Free!

Email Address:
* URL:
*
*Indicates Mandatory Field

Terms & Conditions

DevWebProDK
FlashNewz
DevWebPro










PHP-APC - Speed Up Your Web Applications!

By Joost de Valk
Expert Author
Article Date: 2007-04-09

As regular readers of this blog might know I have written quite some tools using the different API's of search engines, and always found them quite useful.

When I was implementing my sitewide search function, one of the things that bothered me that it was a bit slow.

I knew that I had seen some caching implementations on the Yahoo PHP developer center, but I hadn't bothered up till then to look at them a bit better.

Now I did, and I found the cacheAPC example to be very, very easy.

It relies on the Alternative PHP Cache, an opcode cache PECL extension for PHP.

I wrote two functions, which I then put in to all my pieces of code which I've published that use a lot of calls to the different API's. The first is curlopen, the function I use to open connections:

function curlopen($request) {
           $ch = curl_init();
           curl_setopt($ch, CURLOPT_URL, $request);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
           curl_setopt($ch, CURLOPT_TIMEOUT, 100);
           curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
           $results = curl_exec ($ch);
           curl_close($ch);
           return $results;
}


The second one is the actual cache function, look at how easy it is:

function request_cache($url, $ttl) {
           if(!$doc = apc_fetch($url)) {
                $doc = curlopen($url);
                if ($doc === false) return false;
                apc_store($url,$doc, $ttl);
           }
           return $doc;
}


It basically does three things:

1. It looks if the requested resource is already in the cache, and if it is, it fetches that;

2. If it's not, it opens it through curlopen and stores it in the cache;

3. It returns the requested data;

As you can see the request_cache function takes two parameters: the request url and the TTL, which, in seconds, determines how long that resource should be cached.

Now if you request a PageRank for a URL, it's fairly safe to set this to 24 hours, and you can see how much requests this saves!

Comments

About the Author:
Joost de Valk is an SEO from Nijmegen, the Netherlands, who works for Onetomarket, an online marketing company. He has experience as a sales manager for several IT companies, is involved in open source projects like WebKit and Mozilla, and is the creator of the biggest online resource on CSS3. Joost blogs about web design and SEO, and writes all sorts of scripts for webmasters.



DevWebProDK is an iEntry, Inc. ® publication - All Rights Reserved Privacy Policy and Legal