Home arrow PHP arrow HTML5 Client-Side Cache in PHP

HTML5 Client-Side Cache in PHP

In this penultimate part of a series, I develop a basic client-side cache class in PHP. It uses the local storage mechanism packaged with HTML5 to save, retrieve and manipulate data in the browser.

TABLE OF CONTENTS:
  1. HTML5 Client-Side Cache in PHP
  2. The HTML5 Client-Side Cache Back-end
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
February 02, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

If you're a conscientious PHP developer who wants to build scalable object-oriented applications, and still don't know what approach to take to make the enhancement process as painless as possible (for yourself or for other developers), then keep reading. You'll want to take a close look at the "Plug-in" pattern. As its name suggests, this simple, yet powerful paradigm will let you create truly "pluggable" programs using only the functionality of Composition and Interfaces. That's all that it takes, really.

What's more, to demonstrate how to implement the pattern in some concrete use cases, in previous parts of this series I developed a really basic application. It utilized the concept of "plug-in" to easily couple additional classes to its existing infrastructure. The application was responsible for rendering different types of objects on screen, ranging from a couple of HTML widgets to JavaScript alert boxes. Of course, the most appealing facet of this expansion process was that it didn't demand that we change a single section of the client class consuming those renderable objects.

Logically, the flexible nature of "Plug-in" makes it suitable to implement in all sorts of situations and environments. Indeed, I left off the last installment developing a caching system, which was able to swap different cache back-ends at runtime. While at this stage, the system is composed of a cache manager and only one cache backend (which turns out to be an APC wrapper), this is about to change. In the lines to come I'm going to create another backend, which will make use of the local storage mechanism that comes bundled with HTML5.

So, are you eager to see how the "Plug-in" pattern can be used in the development of a cache library which will be able to cache data in the server and in the client with the same ease? Well, get rid of your anxiety and start reading!

Using the "Plug-in" pattern in the construction of an extensible cache system:  a brief look at the system in its current state

Before I begin building the client-side cache backend mentioned in the introduction, I'd like to spend a few moments reintroducing the source classes (and the interface) that comprise the cache system developed in the previous installment of the series. In doing so, you'll be able to understand more easily how the implementation of a "plug-in" schema can turn this system into an application whose functionality can be easily extended.

First, here's the definition of a generic cache backend, which happens to be an interface called "Cacheable." Take a look at it:

(Cache/Cacheable.php)

<?php

namespace Cache;

interface Cacheable
{
 public function set($key, $data);
 public function get($key);
 public function delete($key);
 public function clear();     
}

As seen above, the "Cacheable" interface defines a contract that must be agreed to by all of the concrete back-ends created from this point onward. Well, the following class is one of the previous interface's implementers. It acts like a simple wrapper for the APC PHP extension. Check it out:

(Cache/ApcCache.php)

<?php

namespace Cache;

class ApcCache implements Cacheable
{
    /**
     * Save data to the cache
     */
    public function set($key, $data)
    {
        if (!apc_store($key, $data)) {
            throw new ApcCacheException('Error saving data with the key ' . $key . ' to the cache.');
        }
        return $this;
    }
   
    /**
     * Get the specified data from the cache
     */
    public function get($key)
    {
        if ($this->exists($key)) {
            if (!$data = apc_fetch($key)) {
                throw new ApcCacheException('Error fetching data with the key ' . $key . ' from the cache.');
            }
            return $data;
        }
        return null;
    }
   
    /**
     * Delete the specified data from the cache
     */
    public function delete($key)
    {
        if ($this->exists($key)) {
            if (!apc_delete($key)) {
                throw new ApcCacheException('Error deleting data with the key ' . $key . ' from the cache.');
            }
        }
        return $this;
    }
   
    /**
     * Check if the specified cache key exists
     */
    public function exists($key)
    {
        return apc_exists($key);
    }
   
    /**
     * Clear the cache
     */
    public function clear($cacheType = 'user')
    {
        return apc_clear_cache($cacheType);
    }       
}

 

(Cache/ApcCacheException.php)

<?php

namespace Cache;

class ApcCacheException extends Exception{}

The logic driving the above "Apc" class is pretty self-explanatory (especially if you've already worked with the APC extension), so let's move on. Pay attention to the definition of the following client class, which permits you to cache data using different cache back-ends, including the one just defined: 

(Cache/CacheHandler.php)

<?php

namespace Cache;

class CacheHandler
{
    protected $_cache;
   
    /**
     * Constructor
     */
    public function __construct(Cacheable $cache)
    {
        $this->_cache = $cache;
    }
   
    /**
     * Add the specified data to the cache
     */
    public function set($key, $data)
    {
        return $this->_cache->set($key, $data);
    }
   
    /**
     * Get the specified data from the cache
     */
    public function get($key)
    {
        return $this->_cache->get($key);
    }
   
    /**
     * Delete the specified data from the cache
     */
    public function delete($key)
    {
        $this->_cache->delete($key);
    }         
}
 
While I have to admit that the implementation of this client class is somewhat naive, it demonstrates how to use the "Plug-in" pattern in the construction of a scalable cache system. If you take a close look at the class' constructor, you'll see that it accepts any implementer of the earlier "Cacheable" interface, which makes simple to create different cache back-ends and inject them straight into the class' internals.

For now, though, there's only one cache backend available for testing, so here's a script that shows how to use it for caching some info about my loyal friend, Julie Smith:

// include the autoloader
require_once 'Autoloader.php';
Autoloader::getInstance();

use CacheApcCache as ApcCache,
    CacheCacheHandler as CacheHandler;

// cache some data using APC
$cacheHandler = new CacheHandler(new ApcCache);
$cacheHandler->set('fname', 'Julie')
             ->set('lname', 'Smith')
             ->set('email', 'julie@domain.com');
            
// display the cached data
echo ' First Name: ' . $cacheHandler->get('fname') .
     ' Last Name: ' . $cacheHandler->get('lname') .
     ' Email: ' . $cacheHandler->get('email');

In the example above, the data is saved to and retrieved from the opcode cache. That's not especially interesting -- but, since the "CacheHandler" class behaves like is a sort of adapter that allows us to switch over multiple cache back-ends at runtime, it'd be a shame not to take advantage of this ability, right?

Well, in the following section I'm going to create a brand new cache backend. It will be capable of caching data in the client through the local storage mechanism included with HTML5.

To see how this cache backend will be developed, move ahead and read the lines to come.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: