カスタム クラスに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);
}
});
試してみて、どうなるか教えてください。