Zend Framework 2 : using ‘caches’ configuration to setting up cache services
Zend Framework 2.2 has Zend\Cache\Service\StorageCacheAbstractServiceFactory that allow us to configure cache services via array configuration. We just need to register the abstract factory and create a config array that represent cache options. I will give you an example if we want to create memcached service.
- register to service manager
//config/autoload/global.php 'service_manager' => array( 'abstract_factories' => array( 'Zend\Cache\Service\StorageCacheAbstractServiceFactory', ) ),
- configure array cache options, for example, I write at config/autoload/cache.local.php
//config/autoload/cache.local.php <?php return array( 'caches' => array( 'memcached' => array( //can be called directly via SM in the name of 'memcached' 'adapter' => array( 'name' =>'memcached', 'options' => array( 'ttl' => 7200, 'servers' => array( array( '127.0.0.1',11211 ) ), 'namespace' => 'MYMEMCACHEDNAMESPACE', 'liboptions' => array ( 'COMPRESSION' => true, 'binary_protocol' => true, 'no_block' => true, 'connect_timeout' => 100 ) ) ), 'plugins' => array( 'exception_handler' => array( 'throw_exceptions' => false ), ), ), ), );
Done, and we can call
$this->getServiceLocator()->get('memcached');
from service that implements ServiceLocatorAwareInterface ( controllers or other service(s)).
Want to check ? Check this at your controller :
//filling cache value public function indexAction() { $this->getServiceLocator()->get('memcached')->setItem('foo', 'bar'); } //retrieve cache value public function retrieveAction() { echo $this->getServiceLocator()->get('memcached')->getItem('foo'); }
If you want to set multi-cache config, just configure, and call them :).
45 comments