在 Zend Framework 2 使用 factory service

在Module.php 加入配置方法
闭包方式:

public function getServiceConfig() {
    return array(
        'factories'=> array(
            'Test\A\B' => function($serviceManager) {
                return new B();
            },
        ),
    );
}	

工厂类方式:

public function getServiceConfig() {
    return array(
        'factories'=> array(
            'Test\A\B' => 'Test\Service\TestFactory',
        ),
    );
}	

编写Test\Service\TestFactory

namespace Test\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class TestFactory implements FactoryInterface {

	/**
 	* Create custom_service
 	*
 	* @param ServiceLocatorInterface $serviceLocator
 	* @return mixed
 	*/
	public function createService(ServiceLocatorInterface $serviceLocator)
	{
    	return $this;
	}

	/**
 	* @return string
 	*/
	public function test() {
    	return 'test';
	}
}

在Controller调用

$this->getServiceLocator()->get('Test\A\B');
0%