Tag Archives: cache

Zend Framework 2 Cache Storage Factories

If you are making an application with Zend Framework 2 (version 2.2) and you need some data Caching – you will find good examples on Zend\Cache usage, but not much about cache initialization or how to store cache configuration.

If you are able to use Google or Bing (or any other modern search engine) – you will find many example how to initiate cache using closures or your own factories or any other fun ideas… but!

ZF2 provides two great ways to store cache configuration for cache storage adapters and initialization of Cache services trough ServiceLocator:

  1. Zend\Cache\Service\StorageCacheFactory
  2. Zend\Cache\Service\StorageCacheAbstractServiceFactory

Both of them are just a Service factories that could be used easily trough ServiceLocator. Storage adapter settings could be set in any configuration file you like (from any module.config.php to config/autoload/any.local.php).

The last one, StorageCacheAbstractServiceFactory, is enabled by default in ZendSkeletonApplication.

If you are using one cache adapter trough all you application, you can just do three things:

1) Add Service with desired name for Cache service which would be initialized by Zend\Cache\Service\StorageCacheFactory somewhere in you Application or Module config file:

return array(
'service_manager' => array(
'factories' => array(
'Application\Cache' =>
'Zend\Cache\Service\StorageCacheFactory',
),
),
);

2) Add Cache Adapter configuration in you configuration files under the key ‘cache’:

return array(
'cache' => array(
'adapter' => array(
'name' => 'filesystem'
),
'options' => array(
'cache_dir' => 'data/cache/',
// other options
),
),
);

3) Use Cache adapter trough Service Locator:

// example from controller
/**
* @var $cache \Zend\Cache\Storage\StorageInterface
*/
$cache = $this->getServiceLocator()->get('Application\Cache');

If you need many different cache adapter with different settings – use StorageCacheAbstractServiceFactory:

1) Add Abstract Service Factory somewhere in you Application or Module config:

return array(
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
),
),
);

2) Add Cache Adapters configuration in you configuration files under the key ‘caches’ by associative array “ServiceName => Settings array”:

return array(
'caches' => array(
'CacheServiceOne' => array(
'adapter' => array(
'name' => 'filesystem'
),
'options' => array(
'cache_dir' => 'data/cache_dir_one/',
// other options
),
),
'CacheServiceTwo' => array(
'adapter' => array(
'name' => 'filesystem'
),
'options' => array(
'cache_dir' => 'data/cache_dir_two/',
// other options
),
),
// more cache adapters settings
),
);

3) Use Cache adapters trough Service Locator in your Application:

// example from controller
/**
* @var $cacheOne \Zend\Cache\Storage\StorageInterface
*/
$cacheOne = $this->getServiceLocator()->get('CacheServiceOne');
// ...
/**
* @var $cacheTwo \Zend\Cache\Storage\StorageInterface
*/
$cacheTwo = $this->getServiceLocator()->get('CacheServiceTwo');

That all: no magic, everything configurable and no closures – only factories.

Немного обновлений

Наконец добрались ручки до своего блога. Смог наконец обновить WordPress до последней версии (на данный момент это 2.3.2) и обновления прошли без проблем.

Отключил Akismet. Он слишком много комментариев стал отправлять в спам. Даже мои собственные комментарии на моём-же блоге стал отправлять в спам. И на это многие жалуются, но никто ничего поделать не может. Так как на любимых блогах все мои комментарии уходят в спам, а изза кол-ва спама их никто не отфильтровывает, я почти перестал комментировать (даже ответные комментарии к моим статьям на Pixel.lt).

В замен к Akismet я поставил Math Comment Spam Protection и Simple Trackback Validation. Пока защищают.

Добавил себе ещё и Feed Statistics. Не люблю я эти FeedBurner и иже с ними, не нравиться мне, что мой Feed кто-то считывает с им присущей частотой и потом показывает от себя. Но статистика то интересует, но так чтоб без измерения у кого больше, поэтому и поставил. Совсем сносно работает.

Добавил и WordPress Gravatars. В комментариях стало куда веселее. По крайней мере виден мой avatar.

Всё-таки вернул wp-cache, так как за ненадобностью и несовместимостью отключил некоторые свои старые плагины. Переписывать под WordPress 2.x мне их не хочется, а обновляться надо.

Так что, если что заметите, то пишите.