在自定义类中实现 ServiceLocatorAwareInterface 接口php
namespace Application\Model; use Zend\ServiceManager\ServiceLocatorAwareInterface; use Zend\ServiceManager\ServiceLocatorInterface; class Demo implements ServiceLocatorAwareInterface{ protected $serviceLocator; /** * Set serviceManager instance * * @param ServiceLocatorInterface $serviceLocator * @return void */ public function setServiceLocator(ServiceLocatorInterface $serviceLocator) { $this->serviceLocator = $serviceLocator; } /** * Retrieve serviceManager instance * * @return ServiceLocatorInterface */ public function getServiceLocator() { return $this->serviceLocator; } public function getServiceConfig() { $this->serviceLocator->get('config'); } }
在Model.php 中把你的自定义类注入到Service Manager, 主要是经过getServiceConfig方法,也可也在module.config.php 中使用service_manage 进行配置数组
public function getServiceConfig() { return array( 'factories'=>array( 'Demo' => function($sm){ $demo = new \Application\Model\Demo(); return $demo; } ) ); }
在indexAction中进行调用this
public function indexAction { //获得Service Manager $sm = $this->getServiceLocator(); //获得自定义demo类 $demo = $sm->get('demo'); $serviceConfig = $demo->getConfig();//经过自定义类demo会获得Service manager中config数组 }