php – ZF2 ServiceManager

我尝试在没有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();

但是当我运行sm.PHP时,我收到一个错误

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');

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...