我真的很困惑什麼時候使用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