Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : using ‘caches’ configuration to setting up cache services

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on October 6, 2013

zf2-zendframework2Zend 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.

  1. register to service manager
    //config/autoload/global.php
    'service_manager' => array(
         'abstract_factories' => array(
                'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
          )
    ),
    
  2. 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 :).

Advertisements