8

カスタム クラス内から ServiceManager インスタンスを取得する方法がわかりません。

コントローラー内では簡単です:

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

Zend\Logここで、いくつかの独立したクラスを作成し、そのクラス内のインスタンスを取得する必要があります。zend フレームワーク v.1 では、静的呼び出しを使用してそれを行いました。

Zend_Registry::get('myCustomLogger');

My\CustomLoggerZF2 でを取得するにはどうすればよいですか?

4

1 に答える 1

12

カスタム クラスに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);
    }
});

試してみて、どうなるか教えてください。

于 2013-07-26T19:07:55.157 に答える