Home arrow PHP arrow Page 2 - Swapping Cache Back-End at Runtime in PHP

Caching opcode in the server - PHP

While the pattern is not as popular as other well-known contenders, like Singleton, Factory and Composite, “Plug-in” is a powerful structural paradigm. It permits developers to create extensible software systems by means of a clever combination of Composition and interfaces. By "interfaces," I mean native ones, or defined in the form of abstract classes.

TABLE OF CONTENTS:
  1. Swapping Cache Back-End at Runtime in PHP
  2. Caching opcode in the server
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
February 07, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Considering that the examples that I plan to set up next will demand the lazy-loading of several classes, in this case I’m going to appeal to the functionality of the same autoloader that was defined during the first part of the series. Its source code was as follows: 

(Autoloader.php)

<?php

class Autoloader
{
    private static $_instance;
   
    /**
     * Get the Singleton instance of the autoloader
     */
    public static function getInstance()
    {
        if (self::$_instance === null) {
            self::$_instance = new self;
        }
        return self::$_instance;
    } 
   
    /**
     * Reset the instance of the autoloader
     */
    public static function resetInstance()
    {
        self::$_instance = null;
    }
   
    /**
     * Class constructor
     */
    private function __construct()
    {
        spl_autoload_register(array(__CLASS__, 'load'));
    }
   
    /**
     * Prevent to clone the instance of the autoloader
     */
    private function __clone(){}
   
    /**
     * Load a given class or interface
     */
    public static function load($class)
    {
        $file = str_replace('', '/', $class) . '.php';
        if (!file_exists($file)) {
            throw new AutoloaderException('The file ' . $file . ' containing the requested class or interface ' . $class . ' was not found.');
        }
        require $file;
        if (!class_exists($class, false) && !interface_exists($class, false)) {
            throw new AutoloaderException('The requested class or interface ' . $class . ' was not found.');
        }
    }  
}

 

(AutoloaderException.php)

<?php

class AutoloaderException extends Exception{}

Having listed the autoloader (and assuming that you already know how it works), the next step is to create an initial example. This example will cache data in the server by injecting an instance of the previous “Apc” class into the client cache handler. It looks like this:

<?php

// 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', 'Susan')
             ->set('lname', 'Norton')
             ->set('email', 'susan@domain.com');
            
// display the cached data
echo ' First Name: ' . $cacheHandler->get('fname') .
     ' Last Name: ' . $cacheHandler->get('lname') .
     ' Email: ' . $cacheHandler->get('email');

As you can see above, caching information on a fictional user is a straightforward, easy-to-grasp process. Nevertheless, the most relevant point to stress here is that the entire caching process is performed in the server, since the “Apc” backend has been passed to the cache handler’s internals.

While this is by far the most common approach to take when caching data, what happens if it’s necessary to use a different backend? Well, this is exactly the situation where the “Plug-in” pattern really shines, as it makes this task trivial.

To elaborate a bit further, in the next segment I’m going to modify the earlier example. This time, it will use the local cache backend to store data in the browser. The best part of all is that this swapping process will be accomplished without having to amend a single portion of client code.

To learn how this new example will be developed, just keep reading.

Caching data in the browser: working with the local cache backend

As I just stated, the only thing left to do in this tutorial is set up an example that shows how easy it is to cache data using the local cache backend instead of the server-side one that you saw before. Well, the following code snippet performs this task in a very simple fashion:

<?php

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

use CacheLocalCache as LocalCache,
    CacheCacheHandler as CacheHandler;

// cache some data using the local cache
$cacheHandler = new CacheHandler(new LocalCache);
$cacheHandler->set('fname', 'Susan')
             ->set('lname', 'Norton')
             ->set('email', 'susan@domain.com');

// fetch the cached data
$cacheHandler->get('fname');
$cacheHandler->get('lname');
$cacheHandler->get('email');

 

/* generates the following 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>
<script>set('fname','Susan');</script>
<script>set('lname','Norton');</script>
<script>set('email','susan@domain.com');</script>
<script>get('fname');</script>
<script>get('lname');</script>
<script>get('email');</script>

*/

While this new example looks nearly identical to the one written in the previous section, its inner workings are radically different. Effectively, this time the cache handler has been supplemented with an instance of the “LocalCache” class, which permits you to save the data corresponding to our friend Susan Norton directly in the browser.

There’s no need to say that the JavaScript code that this example generates behind the scenes can be improved (especially the implementation of the “set()” local storage method). However, I guess that I already made my point demonstrating how the “Plug-in” pattern can be really helpful in the construction of a flexible caching system.

So, what are you waiting for? Go ahead and begin using it in your own PHP applications! 

Final thoughts

As the old saying goes, nothing lasts forever, and this series certainly isn’t an exception. But overall, the experience has been enriching and also fun. I explained in a step-by-step fashion the theoretical concepts that surround the implementation of the “Plug-in” pattern in PHP, and how to use this paradigm in a couple of specific cases.

When it comes down to developing applications that need to be scaled up in the future, certainly there are several approaches you can take. Each has its own pros and cons. However, the “Plug-in” pattern is quite possibly one of the most appealing and elegant, as it combines efficiency with a fairly simple implementation.

So, if you’re planning to build a custom library, a web application or a full-stacked framework whose functionality can be easily extended, the “Plug-in” approach is definitely an option to consider.

See you in the next PHP tutorial!



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