私がサービスを持っているとしましょう:
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;
}
)
)
私の質問はなぜですか?2番目のアプローチが最初のアプローチよりも優れているのはなぜですか?そしてそれはどういう意味controller is dependent of the service
ですか?
ありがとう