在自定義類中實現 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數組 }