ZF2 – Service Manager

The Service Manager for ZF2 is the new Zend_Registry from ZF1.  This class will allow you to create factories on the fly, but more importantly, will allow you to inject simple setups into your application.  Databases, and Cache are the two examples that I’ll use to show the examples of how easy it will be to access these objects from everywhere in your application.

return array(
    'modules' => array(
    'module_listener_options' => array(
        'config_cache_enabled' => false,
        'cache_dir' => 'data/cache',
        'config_glob_paths'    => array(
        'module_paths' => array(
    'service_manager' => array(
        'factories' => array(
            'ZendCacheStorageFactory' => function() {
                return ZendCacheStorageFactory::factory(
                        'adapter' => array( 
                            'name' => 'filesystem', 
                            'options' => array( 
                                'dirLevel' => 2, 
                                'cacheDir' => 'data/cache',
                                'dirPermission' => 0755,
                                'filePermission' => 0666,
                                'namespaceSeparator' => '-db-'
                        'plugins' => array('serializer'), 
        'aliases' => array(
            'cache' => 'ZendCacheStorageFactory',

Notice that there’s a Closure function for the factory.  If you’ve run into the error that the class you’re trying to create is not a valid ZendServiceManagerAbstractFactoryInterface, then you simply have to wrap the object you’re going to return in a Closure function to fix.


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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s