Soflomo\Cache: manage your ZF2 cache services

This week is quite a productive week and today Soflomo\Cache is released. Caching is an essential part in scaling your application, but Zend Framework 2 was missing a utility to manage your caches. Until now!

During deployments we usually flushed the cache in a tedious and cumbersome way by directly accessing the apc_* functions in a custom script. This could certainly be improved and so we wrote a command line utility to manage all our cache services.

What is a cache service?

The framework knows a concept of abstract factories. For caching, there is the StorageCacheAbstractServiceFactory. Enable the factory and you are able to define caches inside the caches key.

'caches' => array(
    'DefaultCache' => array(
        'adapter' => array(
            'name'    => 'apc',
            'options' => array(
                'namespace' => 'foobar',
            ),
        ),
    ),
),

All these caches can be used as service, for example with dependency injection:

class MyFactory implements FactoryInterface
{
    public function createService(ServiceLocator $sl)
    {
        $cache   = $sl->get('DefaultCache');
        $service = new MyService($cache);

        return $service;
    }
}

Overview of the commands

All commands are documented in the README, but here is a shortlist of the most important features:

php public/index cache --flush DefaultCache

Will completely flush the DefaultCache cache. If you have a single cache defined, you can leave the service name:

php public/index cache --flush

In the case you have multiple caches and you don’t specify a single cache, Soflomo\Cache will ask which cache to flush.

Soflomo\Cache asks which cache to flush

You also notice non-reversible operations (like --flush) have a confirmation dialog to confirm. You can get into non-interactive mode by using --force or -f.

Clearing by namespace (so not the complete APC cache is cleared), you can use --by-namespace:

php public/index cache --clear --by-namespace=foobar

An (in my opinion) neat add-on: Soflomo\Cache does not only handle cache services inside your application, it can also delete the merged configuration and module map.

php public/index cache --clear-config
php public/index cache --clear-module-map

But both commands only succeed if you have the options enabled in your application.config.php.

Error when configuration is not enabled

Enjoy using the module. Currently the code is not the most beautiful piece I have ever written, but I am open for improvements!