假设我有一项服务:
namespace Helloworld\Service;
class GreetingService
{
public function getGreeting()
{
if(date("H") <= 11)
return "Good morning, world!";
else if (date("H") > 11 && date("H") < 17)
return "Hello, world!";
else
return "Good evening, world!";
}
}
我为它创建了一个可调用的
public function getServiceConfig()
{
return array(
'invokables' => array(
'greetingService'
=> 'Helloworld\Service\GreetingService'
)
);
}
然后在我的控制器中我可以这样做:
public function indexAction()
{
$greetingSrv = $this->getServiceLocator()
->get('greetingService');
return new ViewModel(
array('greeting' => $greetingSrv->getGreeting())
);
}
据说这使控制器依赖于服务(和 ServiceManager)
更好的解决方案是为该服务创建工厂或在 ServiceManager 中返回一个闭包并在控制器中创建一个设置器:
class IndexController extends AbstractActionController
{
private $greetingService;
public function indexAction()
{
return new ViewModel(
array(
'greeting' => $this->greetingService->getGreeting()
)
);
}
public function setGreetingService($service)
{
$this->greetingService = $service;
}
}
和
'controllers' => array(
'factories' => array(
'Helloworld\Controller\Index' => function($serviceLocator) {
$ctr = new Helloworld\Controller\IndexController();
$ctr->setGreetingService(
$serviceLocator->getServiceLocator()
->get('greetingService')
);
return $ctr;
}
)
)
我的问题是为什么?为什么第二种方法比第一种更好?这意味着什么controller is dependent of the service
?
谢谢