我在弄清楚如何从自定义类中获取ServiceManager实例时遇到了麻烦。
在控制器内部很容易:
$this->getServiceLocator()->get('My\CustomLogger')->log(5, 'my message');
现在,我创建了一些独立的类,并且需要Zend\Log
在该类中检索实例。在zend Framework v.1中,我通过静态调用做到了这一点:
Zend_Registry::get('myCustomLogger');
如何My\CustomLogger
在ZF2中检索?
使您的自定义类实现ServiceLocatorAwareInterface
。
当您使用ServiceManager实例化它时,它将看到正在实现的接口并将其自身注入到类中。
现在,您的班级将有服务经理在其操作期间与之一起工作。
<?php
namespace My;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
class MyClass implements ServiceLocatorAwareInterface{
use ServiceLocatorAwareTrait;
public function doSomething(){
$sl = $this->getServiceLocator();
$logger = $sl->get( 'My\CusomLogger')
}
}
// later somewhere else
$mine = $serviceManager->get( 'My\MyClass' );
//$mine now has the serviceManager with in.
为什么要这样做?
这仅在Zend \ Mvc的上下文中有效,因为您提到了控制器,所以我假设您正在使用Zend \ Mvc。
之所以有效,是因为Zend\Mvc\Service\ServiceManagerConfig
向ServiceManager添加了初始化程序。
$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
if ($instance instanceof ServiceLocatorAwareInterface) {
$instance->setServiceLocator($serviceManager);
}
});
试试看,让我知道会发生什么。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句