Zend Framework 2 – Cache Example

In this post, i will show you how to cache your data in ZF2 using “filesystem” adapter.We can directly instance the “ZendCacheStorageAdapter* ” classes or you can implement factory . It’s always better to create caching adapters by using factory for avoiding to do it manually for each time.With the help of service locator we can easily use the service factories. So lets setup blow are the steps

1. Go to config/application.config.php then add the service_manager array item as show below Change the settings of Cache adapter as your needs.

return array(
    // This should be an array of module namespaces used in the application.
    'modules' => array(

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => array(
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => array(
       'service_manager' => array(
        'factories' => array(
            'ZendCacheStorageFactory' => function() {
                return ZendCacheStorageFactory::factory(
                        'adapter' => array(
                            'name' => 'filesystem',
                            'options' => array(
                                'dirLevel' => 2,
                                'cacheDir' => 'data/cache',
                                'dirPermission' => 0755,
                                'filePermission' => 0666,
                                'namespaceSeparator' => '-db-'
                        'plugins' => array('serializer'),
        'aliases' => array(
            'cache' => 'ZendCacheStorageFactory',

How to use

Here is the simple example method, Just grab the concept from the blow controller method. Read the comment for better understanding.

		// set unique Cache key
		$key    = 'unique-cache-key';
		// get the Cache data
        $result = $cache->getItem($key, $success);
		if (!$success) {
		// if not set the data for next request
			$result = 'arjun';
			$cache->setItem($key, $result);
		// result
        echo $result;
        return new ViewModel();

That’s it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

DMCA.com Protection Status