我尝试在没有MVC模块的情况下使用zf2中的ServiceManager.我有两个文件:classServiceManager.PHP和sm.PHP.
1)classServiceManager.PHP:
namespace ZF2;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use \invalidargumentexception;
class classServiceManager implements ServiceLocatorAwareInterface{
protected $serviceLocator;
function __construct(){
//echo "SM: ". $this->getServiceLocator()->get('sm');
echo "SM: ".$this->serviceLocator->get('sm');
}
function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
$this->serviceLocator = $serviceLocator;
}
function getServiceLocator() {
return $this->serviceLocator;
}
}
2)sm.PHP
$config = array(...);
require_once 'Zend/Loader/AutoloaderFactory.PHP';
Zend\Loader\AutoloaderFactory::factory($config);
......
use ZF2\classServiceManager;
$serviceManager = new ServiceManager();
$serviceManager->setService('sm', 'aaa');
$a = new classServiceManager();
Fatal error: Call to a member function get() on a non-object....
解决方法:
By default, the Zend Framework MVC registers an initializer that will inject the ServiceManager instance, which is an implementation of Zend\ServiceManager\ServiceLocatorInterface, into any class implementing Zend\ServiceManager\ServiceLocatorAwareInterface.
所以ServiceLocatorAwareInterface仅用于MVC应用程序.
如果你想在没有MVC的情况下使用zf2的ServiceManager,你需要自己创建一个ServiceManager
这是我的
namespace Westdc\Service;
use Zend\ServiceManager\ServiceManager as Zend_ServiceManager;
class ServiceManager {
private $serviceManager;
function __construct()
{
$this->serviceManager = new Zend_ServiceManager;
$this->serviceManager->addAbstractFactory(new ServiceFactory);
$configService = $this->serviceManager->get('ConfigService');
$invoked_services = $configService->get('service.invoked.ini');
foreach($invoked_services as $k=>$v) {
$this->serviceManager->setInvokableClass($k, $v);
}
}
public function addKey($key,$value = "")
{
if(!empty($value))
$this->serviceManager->$key($value);
else
$this->serviceManager->$key();
}
public function setServiceManager(Zend_ServiceManager $service)
{
$this->serviceManager = $service;
}
public function getServiceManager()
{
return $this->serviceManager;
}
}
这是我使用它的例子
use Westdc\Service\ServiceManager;
$serviceManager = new ServiceManager();
$serviceManager = $serviceManager->getServiceManager();
$authService = $serviceManager->get('Auth');
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。