Skip to content

Zend Framework 2 – Cache Example

Last updated on December 21, 2022

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

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

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

    // 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(
            './module',
            './vendor',
        ),
    ),
       'service_manager' => array(
        'factories' => array(
            'ZendCacheStorageFactory' => function() {
                return ZendCacheStorageFactory::factory(
                    array(
                        '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 a better understanding.

getServiceLocator()->get('cache');
		// 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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments