Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Using Component as Module

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on May 17, 2016

If you use latest zendframework by requiring “zendframework/zendframework”: “^2.5”, You will now get various zendframework components tagged as ~2.7 or ~2.8 as per-component has own life based on each evolution. Interestingly, many components that has services, now act as module. You can check the components on zendframework blog post. In the components mentioned in the post, they will have Module class that uses ConfigProvider class when registering services. If you don’t get the Module class yet inside the components mentioned, you need to run:

composer update

We can consume the components as modules, for example, in config/application.config.php, you can define:

return [
    'modules' => [
    //  other configs here 

If you check the services registered in Zend\Cache, you will get Zend\Cache\Service\StorageCacheAbstractServiceFactory::class that registered in abstract_factories, that allow us to configure cache services via array with ‘caches’ config as limbo when no services that has name inside the ‘caches’ array registered yet. So, for example, we have configured ‘caches’ config:

// config/autoload/global.php
return [
    // ...
    'caches' => [
        'cache_file' => [
            'adapter' => 'filesystem',
            'lifetime' => 7200,
            'options' => [
                'cache_dir' => './data/cache',

We have cache_file as service name that utilize filesystem cache adapter as config above. We then can just consume the cache_file via service manager:

// assumption: $services is a Zend\ServiceManager\ServiceManager 
// that pulled during Mvc workflow
$services->get('cache_file')->setItem('foo', 'fooValue');
echo $services->get('cache_file')->getItem('foo');


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: