在文档中说:"默认情况下,Zend框架MVC注册了一个初始化器,该初始化器将把ServiceManager实例注入任何实现ZendServiceManagerServiceLocatorInterface的类中,该实例是ZendServiceManagerServiceLocatorAwareInterface的实现。"
所以我试了这个:
interface ModelResourceInterface extends ServiceLocatorAwareInterface
{
}
interface ServiceModelResourceInterface extends ModelResourceInterface
{
public function fetch($uri, $method, $parameters, $options, $encodeType);
}
namespace SsportsModelResourceServiceHttp;
use SsportsModelResourceServiceServiceModelResourceInterface;
use ZendServiceManagerServiceLocatorInterface;
use ZendHttpClient;
use ZendHttpRequest;
use SsportsModelResourceServiceConnectionException;
abstract class AbstractHttpServiceModelResource implements ServiceModelResourceInterface
{
/**
*
* @var ZendServiceManagerServiceLocatorInterface;
*/
protected $serviceLocator;
/**
* Constructor
*/
function __construct()
{
$this->init();
}
/**
* Extend Constructor
*/
public function init()
{}
/**
* (non-PHPdoc)
*
* @see ZendServiceManagerServiceLocatorAwareInterface::setServiceLocator()
*
*/
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
/**
* (non-PHPdoc)
*
* @see SsportsModelResourceServiceServiceModelResourceInterface::fetch()
*
*/
public function fetch($uri, $method, $parameters = null, $options = null, $encodeType = null)
{
try {
//something raise RuntimeException
} catch (RuntimeException $e) {
$this->getServiceLocator()->get('LogWeb');
throw new ConnectionException();
}
}
/**
* (non-PHPdoc)
*
* @see ZendServiceManagerServiceLocatorAwareInterface::getServiceLocator()
*
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
}
我用一些模型资源类扩展这个抽象类,并运行它,并抛出一个异常,说我在非对象上调用get。
似乎服务管理器没有被注入到我的抽象类,getServiceLocator的返回是NULL。
我错过了什么来弥补吗?
您尝试过使用服务定位器特性吗?
可以在ZendServiceManagerServiceLocatorAwareTrait中找到
要使用trait,请执行以下操作
class Class1
{
use ZendServiceManagerServiceLocatorAwareTrait;
}
你可以访问服务定位器,或者至少当我需要加载服务定位器时,我必须这样做。