我真的很困惑什么时候使用getServiceLocator和什么时候不使用。 作为一个例子:ZF2什么时候使用getServiceLocator()什么时候不到
+ Module
-+ Helloworld
--+ src
---+ Controller
----+ IndexController.php
----+ IndexControllerFactory.php
---+ Service
----+ LogginService.php
----+ GreetingService.php
----+ GreetingServiceFactory.php
GreetingServiceFactory.php具有内容:
<?php
namespace Helloworld\Service;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class GreetingServiceFactory implements FactoryInterface
{
public function createService (ServiceLocatorInterface $serviceLocator)
{
$greetingService = new GreetingService();
$greetingService->setEventManager($serviceLocator->get('eventManager'));
$loggingService = $serviceLocator->get('loggingService');
$greetingService->getEventManager()->attach('getGreeting', array(
$loggingService,
'onGetGreeting'
));
return $greetingService;
}
}
而且IndexControllerFactory.php有内容:
<?php
namespace Helloworld\Controller;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class IndexControllerFactory implements FactoryInterface
{
public function createService (ServiceLocatorInterface $serviceLocator)
{
$ctr = new IndexController();
$ctr->setGreetingService($serviceLocator->getServiceLocator()
->get('greetingService'));
return $ctr;
}
}
正如你所看到的,我需要$服务定位 - >我的ControllerFactory中的getServiceLocator(),但不是在我的ServiceFactory中。为什么?两者都使用相同的接口ServiceLocatorInterface,它甚至没有定义getServiceLocator()方法。
module.config.php:
'controllers' => array(
'factories' => array(
'Helloworld\Controller\Index' => 'Helloworld\Controller\IndexControllerFactory'
)
)
,
'service_manager' => array(
'invokables' => array(
'loggingService' => 'Helloworld\Service\LoggingService'
),
'factories' => array(
'greetingService'=> 'Helloworld\Service\GreetingServiceFactory'
),
)
我会很感激任何澄清:)
有一个愉快的一天!
你用什么工具创建该图?看起来不错。 – Leven 2013-10-22 18:32:00
@Leven就是YUML – Ocramius 2013-10-22 19:43:40