사용자 지정 클래스 내부에서 ServiceManager 인스턴스를 가져 오는 방법을 알아내는 데 문제가 있습니다.
컨트롤러 내부는 다음과 같습니다.
$this->getServiceLocator()->get('My\CustomLogger')->log(5, 'my message');
이제 몇 개의 독립적 인 클래스를 만들고 Zend\Log
해당 클래스 내에서 인스턴스 를 검색해야합니다 . zend 프레임 워크 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\Service\ServiceManagerConfig
ServiceManager에 이니셜 라이저를 추가 하기 때문에 작동 합니다.
$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
if ($instance instanceof ServiceLocatorAwareInterface) {
$instance->setServiceLocator($serviceManager);
}
});
시도해보고 무슨 일이 일어나는지 알려주세요.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다