You can then proceed and configure the service manager to generate proxies instead of real services:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

$serviceManager=new\Zend\ServiceManager\ServiceManager();$config=array('lazy_services'=>array(// mapping services to their class names is required// since the ServiceManager is not a declarative DIC'class_map'=>array('buzzer'=>'MyApp\Buzzer',),),);$serviceManager->setService('Config',$config);$serviceManager->setInvokableClass('buzzer','MyApp\Buzzer');$serviceManager->setFactory('LazyServiceFactory','Zend\ServiceManager\Proxy\LazyServiceFactoryFactory');$serviceManager->addDelegator('buzzer','LazyServiceFactory');

This will tell the service manager to use the LazyServiceFactory delegator factory to
instantiate the buzzer service.

As you may have noticed, the standard setup for the LazyServiceFactory requires you to define
a Config service. That’s because the functionality was thought to be easily integrated into
Zend\Mvc.

You can now simply retrieve the buzzer:

1
2
3

$buzzer=$serviceManager->get('buzzer');echo$buzzer->buzz();

To verify that the proxying occurred correctly, you can simply run the following code, which should delay
the 5 seconds wait time hardcoded in Buzzer::__construct until Buzzer::buzz is invoked:

This is the config structure expected by Zend\ServiceManager\Proxy\LazyServiceFactoryFactory:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

returnarray('lazy_services'=>array(// map of service names and their relative class names - this// is required since the service manager cannot know the// class name of defined services upfront'class_map'=>array(// 'foo' => 'MyApplication\Foo',),// directory where proxy classes will be written - default to system_get_tmp_dir()'proxies_target_dir'=>null,// namespace of the generated proxies, default to "ProxyManagerGeneratedProxy"'proxies_namespace'=>null,// whether the generated proxy classes should be written to disk or generated on-the-fly'write_proxy_files'=>false,),);