ZF2:如何从自定义类中获取 ServiceManager 实例 [英] ZF2: how do I get ServiceManager instance from inside the custom class

查看:28
本文介绍了ZF2:如何从自定义类中获取 ServiceManager 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble figuring out how to get ServiceManager instance from inside the custom class.

在控制器内部很容易:

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

现在,我创建了几个独立的类,我需要在该类中检索 Zend\Log 实例.在 Zend 框架 v.1 中,我通过静态调用做到了:

Now, I created a few independent classes and I need to retrieve Zend\Log instance inside that class. In zend framework v.1 I did it through static call:

Zend_Registry::get('myCustomLogger');

如何在 ZF2 中检索 My\CustomLogger?

How can I retrieve the My\CustomLogger in ZF2?

推荐答案

使您的自定义类实现 ServiceLocatorAwareInterface.

Make your custom class implement the ServiceLocatorAwareInterface.

当您使用 ServiceManager 实例化它时,它会看到正在实现的接口并将其自身注入到类中.

When you instantiate it with the ServiceManager, it will see the interface being implemented and inject itself into the class.

您的班级现在将有服务经理在其运营期间与之合作.

Your class will now have the service manager to work with during its operations.

<?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 的上下文中有效,我假设您正在使用它,因为您提到了控制器.

This works only in the context of the Zend\Mvc, which I assume you're using because you mentioned a controller.

之所以有效,是因为 Zend\Mvc\Service\ServiceManagerConfig 向 ServiceManager 添加了一个初始化程序.

It works because the Zend\Mvc\Service\ServiceManagerConfig adds an initializer to the ServiceManager.

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

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

Give it a try and let me know what happens.

这篇关于ZF2:如何从自定义类中获取 ServiceManager 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆