ZF2:如何从自定义类中获取ServiceManager实例

时间:2013-07-26 18:42:39

标签: php zend-framework zend-framework2

我无法弄清楚如何从自定义类中获取ServiceManager实例。

在控制器内部很容易:

$this->getServiceLocator()->get('My\CustomLogger')->log(5, 'my message');

现在,我创建了一些独立的类,我需要在该类中检索Zend\Log实例。 在zend框架v.1中,我通过静态调用完成了它:

Zend_Registry::get('myCustomLogger');

如何在ZF2中检索My\CustomLogger

1 个答案:

答案 0 :(得分:11)

让自定义类实现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\Service\ServiceManagerConfig为ServiceManager添加了初始化程序。

$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
    if ($instance instanceof ServiceLocatorAwareInterface) {
        $instance->setServiceLocator($serviceManager);
    }
});

尝试一下,让我知道会发生什么。

相关问题