Home arrow PHP arrow Page 2 - HTML5 Client-Side Cache in PHP

The HTML5 Client-Side Cache Back-end - 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 the words "local storage" don't ring any bells for you, let me remind you that it refers to a feature bundled with HTML5 (and surprisingly supported by most major browsers, including Internet Explorer 8+). Local storage permits you to store up to 5 MB of data in the browser via a set of intuitive JavaScript methods. In fact, I covered the use of "local storage" in a series published here at the Developer Shed network. If you're interested in learning more about it, I suggest you to start with the "HTML5 Local Storage Overview".

Having explained what "local storage" is, let me focus your attention on the following cache backend class, which acts like a proxy for the methods provided by this mechanism: 

(Cache/LocalCache.php)

<?php

namespace Cache;

class LocalCache implements Cacheable
{
    /**
     * Constructor (defines a basic set of local storage JavaScript functions)
     */
    public function __construct()
    {
        $js = <<<JAVASCRIPT
        <script>
        if ('localStorage' in window && window['localStorage'] !== null) {
            function set(key, data) {
                localStorage.setItem(key, data);
            }
            function get(key) {
                return localStorage.getItem(key);
            }
            function remove(key) {
                localStorage.removeItem(key);
            }
            function clear() {
                localStorage.clear();
            }
        }  
        </script>n
JAVASCRIPT;
        echo $js;
    }
   
    /**
     * Save an item to the local storage
     */
    public function set($key, $data)
    {
        if (!is_string($key) || !is_string($data)) {
            throw new LocalCacheException('The supplied key and data for the set() method must be strings.');  
        }  
        echo '<script>set('' . $key . '',' . ''' . $data . '');</script>' . "n";
        return $this;
    }
   
    /**
     * Get an item from the local storage (basic implementation)
     */
    public function get($key)
    {
        if (!is_string($key)) {
            throw new LocalCacheException('The supplied key for the get() method must be a string.'); 
        }
        echo '<script>get('' . $key . '');</script>' . "n";
    }
}

While at first sight it seems that the underlying logic of the previous "LocalCache" class is rather hard to grasp, this is a misconception, believe me. All that this class does is generate the JavaScript code required for using the "localStorage" HTML5 object. As seen above, most of this automatic generation process is accomplished within the class' constructor, while the remaining "set()" and "get()" methods are simple proxies for the appropriate methods provided by the pertinent object.

Of course, if you're a sharp observer, you may have noticed that there's a tiny catch here: the implementation of the "get()" method is incomplete, as it effectively fetches data from the local storage, but it does nothing especially useful with it. I've done this deliberately, so that you can replace my implementation with your own -- which for instance, could assign the data to a JavaScript variable for further manipulation. It's up to you to decide the behavior that this method will have in the end.

So far, so good. In its current state, the "LocalCache" class is capable of saving and (partially) retrieving data from the local storage. If you test the class right now, however, you'll get an ugly fatal error from the PHP engine, as the class doesn't fully implement all of the methods declared by the earlier "Cacheable" interface.

To address this issue, in the upcoming segment I'm going to complete the definition of the "LocalCache" class by adding these missing methods to it. So keep reading.

Deleting cached items and clearing the local storage: adding a couple of methods to the "LocalCache" class

As promised in the preceding section, here's the complete version of the "LocalCache" class, which now provides a concrete implementation for all of the methods declared by the "Cacheable" interface:

(Cache/LocalCache.php)

<?php

namespace Cache;

class LocalCache implements Cacheable
{
    /**
     * Constructor (defines a basic set of local storage JavaScript functions)
     */
    public function __construct()
    {
        $js = <<<JAVASCRIPT
        <script>
        if ('localStorage' in window && window['localStorage'] !== null) {
            function set(key, data) {
                localStorage.setItem(key, data);
            }
            function get(key) {
                return localStorage.getItem(key);
            }
            function remove(key) {
                localStorage.removeItem(key);
            }
            function clear() {
                localStorage.clear();
            }
        }  
        </script>n
JAVASCRIPT;
        echo $js;
    }
   
    /**
     * Save an item to the local storage
     */
    public function set($key, $data)
    {
        if (!is_string($key) || !is_string($data)) {
            throw new LocalCacheException('The supplied key and data for the set() method must be strings.');  
        }  
        echo '<script>set('' . $key . '',' . ''' . $data . '');</script>' . "n";
        return $this;
    }
   
    /**
     * Get an item from the local storage (basic implementation)
     */
    public function get($key)
    {
        if (!is_string($key)) {
            throw new LocalCacheException('The supplied key for the get() method must be a string.'); 
        }
        echo '<script>get('' . $key . '');</script>' . "n";
    }
   
    /**
     * Remove an item from the local storage
     */
    public function delete($key)
    {
        if (!is_string($key)) {
            throw new LocalCacheException('The supplied key for the delete() method must be a string.');     
        }
        echo '<script>remove('' . $key . '');</script>' . "n";
    }
   
    /**
     * Clear the local storage
     */
    public function clear()
    {
        echo '<script>clear();</script>' . "n";
    }             
}

 

(Cache/LocalCacheException.php)

<?php

namespace Cache;

class LocalCacheException extends Exception{}
 
Mission accomplished. If you want to give the "LocalCache" class a try, everything should work like a charm -- of course, don't forget to include the "Cacheable" interface in your testing script as well. But aside from these minor details, which you'll surely be aware of, the most relevant thing to stress here is that now there are two different cache back-ends that can be injected into the earlier cache handler. This fact proves that it's fairly simple to create an extensible caching system from scratch, thanks to the clever use of the "Plug-in" pattern.   

As usual, the best way to demonstrate the flexibility of this system is by example. Therefore, in the last tutorial of this series I'm going to create one that will show how easy it is to swap the two previously defined cache back-ends. 

Final thoughts

In this penultimate chapter of the series, I went through the development of a basic client-side cache class, which uses the local storage mechanism packaged with HTML5 to save, retrieve and manipulate data in the browser.

Although it's fair to say that the functionality of this sample class can be extended (which I'm leaving as homework for you), it's useful for illustrating how to build a "pluggable" caching library, even though it currently uses a couple of cache back-ends.

As I said before, though, it's mandatory to set up an example that puts these back-ends to work side by side, so you can see how simple it is to interchange them at runtime. That's precisely the topic that I plan to cover in the last installment of the series.

So, here's my piece of advice: don't miss the final part! 



 
 
>>> 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: