Fork me on GitHub

11.1 The Importance of Cache

As we know, cache is important. And it' more important to know when and how to use cache properly in our application. Let's explore cache in deeop.

11.2 Simple Cache

Simple cache here means file cache in PhalApi. The advantage of file cache is simple and common, and its shortcoming is obvious, including heavy I/O, unabled to be used in distributed machines.

After register PhalApi_Cache_File into DI, we can use cache as we want.

//$ vim ./Public/init.php 
DI()->cache = new PhalApi_Cache_File(array('path' => API_ROOT . '/Runtime', 'prefix' => 'demo'));

// set a cache
DI()->cache->set('thisYear', 2015, 600);

// get the cache
echo DI()->cache->get('thisYear');

// delete the cache
DI()->cache->delete('thisYear');

11.3 NoSQL Cache

NoSQl is more and more popular in these years, such as Memcache/Memcached, Redis. They are free with high-performance, and stored in distributed memory.

Here is an example of Memcached.

DI()->cache = new PhalApi_Cache_Memcached(array('host' => '127.0.0.1', 'port' => 11211, 'prefix' => 'demo_'));

// set a cache
DI()->cache->set('thisYear', 2015, 600);

// get the cache
echo DI()->cache->get('thisYear');

// delete the cache
DI()->cache->delete('thisYear');

Please note that we use prefix demo_ in cace of cache key conflict in the same memcached instance.

11.4 Multiple Cache

In more complicate business situation, we need more powerful cache strategy. That's to say, we need multiple cache, not just only single cache.

An interesting problem arises here: how can we organize multiple cache in an elegant way?

For example, how can we use the file cache and memcached cache above together, without changing any client usage?

Let's introduce PhalApi_Cache_Multi. With the help of PhalApi_Cache_Multi, we can re-register DI()->cache as below.

$cache = PhalApi_Cache_Multi();

$mcCache = new PhalApi_Cache_Memcached(array('host' => '127.0.0.1', 'port' => 11211, 'prefix' => 'demo_'));
$cache->addCache($mcCache);

$fileCache = new PhalApi_Cache_File(array('path' => API_ROOT . '/Runtime', 'prefix' => 'demo'));
$cache->addCache($fileCache);

DI()->cache = $cache;

Then the clients who use DI()->cache do not change anything to keep everything working well.

// set a cache
DI()->cache->set('thisYear', 2015, 600);

// get the cache
echo DI()->cache->get('thisYear');

// delete the cache
DI()->cache->delete('thisYear');

11.5 UML Static Structure

We use some design patterns here. The main pattern is Composite Pattern.

The inheritance structure is very clear. On the left side is multiple cache, in the middle is special cache i.e. None-Object pattern, while on the right side is implements cache.

11.6 Extend Your Cache

When need to extend an new cache, you just have to implement interface PhalApi_Cache.