在自定义类中实现 ServiceLocatorAwareInterface 接口
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中进行调用
public function indexAction{ //得到Service Manager $sm = $this->getServiceLocator(); //得到自定义demo类 $demo = $sm->get('demo'); $serviceConfig = $demo->getConfig();//通过自定义类demo会得到Service manager中config数组}