1

I have a factory method class that returns a cache system class (pseudo code):

class CacheFactory
{
    public static function get($type) {
        switch ($type) {
            case 'memcache': 
                return new Memcache();
            case 'redis': 
                return new Redis();
            case 'default': 
                return new Void();
        }
    }
}

The cache classes implements simple get() and set() methods (it uses an abstract class defining the common methods) that allows me to easily switch cache systems if needed. The normal use will be like:

$cache = CacheFactory::get('redis');
$value = $cache->get('key');
...etc

I want to have a setting to enable/disable the cache, but I don't want to add conditionals in the code asking if the cache is enabled or not everywhere. So I was thinking in returning a Void() object that implements the abstract class methods so it will be used when the cache is disabled, the class will look like this:

class Void extends ACache
{
    public function get(){};
    public function set(){};
}

Would this be a good approach? How would you think will be the best way to handle the enabled/disabled setting without adding conditionals in the actual implementation?

Thanks!

Salomon Zhang
  • 1,553
  • 3
  • 23
  • 41
  • 2
    This is the NullObject pattern. http://www.oodesign.com/null-object-pattern.html – Mike Stockdale Apr 13 '14 at 02:20
  • Caching is a cross-cutting concern, so is best addressed via *Read-Through Caches*, also more generally known as *Decorators*. See here for more details (just mentally replace the word *Logging* with *Caching*): http://stackoverflow.com/a/1709048/126014 See also http://stackoverflow.com/a/7906547/126014 – Mark Seemann Apr 13 '14 at 07:50
  • @MarkSeemann a couple of questions: 1. Decorators should be used in the actual implementation so the factory method here will still work right? For example: $object = new CacheDecorator(new Thing()); The factory could be added as Dependency Injection or inside the CacheDecorator. 2. If I add a cache decorator as your logging example, how do you handle when values are cached? For example, if I use the cache decorator doStuff() method and the value is in cache I wouldn't call the doStuff() method of innerThing and that would break the chain for other decorators, please correct me if I'm wrong. – user3528035 Apr 14 '14 at 14:55
  • 1. Sounds right. 2. True. Some Decorators 'break' the chain; a caching Decorator would often do so, so it's important to compose them in the right order. – Mark Seemann Apr 14 '14 at 18:20

0 Answers0