Description:
You can use this class to simply cache your data with Memcache in PHP.
Requirements
- PHP 5.3 or higher (you can change "__construct" to "cache" to make it work in older versions)
- Memcache extention installed (how to install the Memcached extention?)
- Memcached installed on a server (how to install Memcached?)
cache.php
Save the code below to a file named cache.php, and include this file in your php code (include "cache.php";)
# Copyright 2012 John Post - StarfixIT
# NOTE: Requires PHP version 5.3 or later with Memcache module
class cache
{
private $host = '127.0.0.1';
private $port = '11211';
private $memcache;
private $lifetime;
private $name;
function __construct($name = false, $lifetime = 600)
{
//Check if Memcache is installed
if(!class_exists("Memcache")){
exit("You need to install memcache");
}
//Check if allready connected to memcached
if (isset($_GLOBALS["memcache"])) {
//Yes, use old connection
$this->memcache = $_GLOBALS["memcache"];
} else {
//No, make new connection
$this->memcache = new Memcache;
$this->memcache->connect($this->host, $this->port);
$_GLOBALS["memcache"] = $this->memcache;
}
//Set global livetime
$this->lifetime = $lifetime;
//Set global name
if ($name !== false) {
$this->name = $this->makeNameOk($name);
}
}
//Public function to set the name
public function setName($name)
{
$this->name = $this->makeNameOk($name);
}
//Public function to set the cache, livetime optional
public function setCache($data, $lifetime = false)
{
$lifetime = $lifetime === false ? $this->lifetime : $this->lifetime;
$this->memcache->set($this->name, $data, MEMCACHE_COMPRESSED, $lifetime);
}
//Public function to get the cache, optional name
public function getCache($name = false)
{
$name = $name === false ? $this->name : $name;
$result = $this->memcache->get($name);
if ($result !== false) {
return $result;
}
return false;
}
//Public function to remove the data from Memcached
public function remove( $name = false )
{
$name = $name === false ? $this->name : $name;
$this->memcache->delete( $name );
}
//Function to create a clean alias
private function makeNameOk($name)
{
return preg_replace('/[^A-Za-z0-9_]/', "", $name);
}
}
Example
//Include Cache class
include "cache.php";
//Open the class with name "myData" and 900 secs lifetime
$cache = new cache("myData", 900);
//Get the data from cache
$data = $cache->getCache();
if( $data === false ){
//if the cache is expired, run the expensive function
$data = very_expensive_function();
//Save the data to cache
$cache->setCache( $data );
echo "Cache set:
";
}else{
echo "Got data from cache:
";
}
//Output the data
echo $data;
//This is just a silly example of an expensive function (takes about 2 seconds)
function very_expensive_function(){
$count = 19500000;
$time_start = microtime(true);
for($i = 0; $i < $count; ++$i);
$i = 0; while($i < $count) ++$i;
return number_format(microtime(true) - $time_start, 3);
}
0 comments:
Post a Comment