以下对我有用。为了使 Zend\Di 与 Zend\ServiceManager 兼容,我从 Zend\Di\Di 扩展了一个 MyLib\Di\Di 类,它实现了 AbstractFactoryInterface。
namespace MyLib\Di;
use Zend\ServiceManager\AbstractFactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class Di extends \Zend\Di\Di implements AbstractFactoryInterface
{
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return true;
}
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
return $this->get($requestedName);
}
}
现在,我可以使用 MyLib\Di\Di 作为 Zend\ServiceManager 的备用抽象工厂。这是我如何创建 IndexController 的示例。IndexController 的依赖项(构造函数参数)是自动注入的。
class Module
{
...
public function getServiceConfig()
{
$this->di = new \MyLib\Di\Di;
$this->configureDi($this->di); // Set up definitions and shared instances
return array(
'abstract_factories' => array($this->di),
);
}
public function getControllerConfig()
{
return array(
'factories' => array(
'Survey\Controller\IndexController' => function() {
return $this->di->get('Survey\Controller\IndexController');
},
),
);
}
}