使用控制器作为服务的具体例子?
Concrete examples of using a controller as a service?
我阅读了文档如何将控制器用作服务。但我不确定这样做的目的是什么。为什么不直接使用服务(class 定义为服务)?
如果有人能给我一些在服务中转换 控制器 的好例子,那就太好了。
经典的 Symfony 控制器使用 Service Locater 模式来引入它的依赖项:
class PersonController
{
public function showAction()
{
$personRepository =
$this->getDoctrine()->getEntityManager()->getRepository('Entity\Person');
$person = $personRepository->find(1);
return new JsonResponse($person);
获取人员存储库要求操作具有相当多的关于如何定位事物的知识。事实上有点神奇。控制器直接绑定到条令和框架基础设施。
这也使得动作难以测试。您必须制作一个容器,然后在 运行 操作之前定义必要的服务。
将其与定义为服务的控制器进行对比,并注入其依赖项:
class PersonController
{
protected $personRepository;
public function __construct($personRepository)
{
$this->personRepository = $personRepository;
}
public function showAction()
{
$person = $this->personRepository->find(1);
操作不再需要知道如何定位存储库。它就在那里。对于测试,只需要制作一个存储库并注入它。干净简单。
我阅读了文档如何将控制器用作服务。但我不确定这样做的目的是什么。为什么不直接使用服务(class 定义为服务)?
如果有人能给我一些在服务中转换 控制器 的好例子,那就太好了。
经典的 Symfony 控制器使用 Service Locater 模式来引入它的依赖项:
class PersonController
{
public function showAction()
{
$personRepository =
$this->getDoctrine()->getEntityManager()->getRepository('Entity\Person');
$person = $personRepository->find(1);
return new JsonResponse($person);
获取人员存储库要求操作具有相当多的关于如何定位事物的知识。事实上有点神奇。控制器直接绑定到条令和框架基础设施。
这也使得动作难以测试。您必须制作一个容器,然后在 运行 操作之前定义必要的服务。
将其与定义为服务的控制器进行对比,并注入其依赖项:
class PersonController
{
protected $personRepository;
public function __construct($personRepository)
{
$this->personRepository = $personRepository;
}
public function showAction()
{
$person = $this->personRepository->find(1);
操作不再需要知道如何定位存储库。它就在那里。对于测试,只需要制作一个存储库并注入它。干净简单。