我怎样才能使用注释将控制器定义为服务?

Ste*_*roz 3 service annotations symfony

这似乎是使用控制器作为服务的最快和最简单的方法,但我仍然缺少一步,因为它不起作用.

这是我的代码:

控制器/服务:

// Test\TestBundle\Controller\TestController.php

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @Route(service="test_service")
 */
class TestController extends Controller {
  // My actions
}
Run Code Online (Sandbox Code Playgroud)

使用 :

// Test\TestBundle\Controller\UseController.php

// ...
public function useAction() {
  $testService = $this->get('test_service');
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我得到了错误

您已请求不存在的服务"test_service".

当我检查服务列表时app/console container:debug,我没有看到我新创建的服务.

我错过了什么?

Jak*_*las 7

SensioFrameworkExtraBundle中的Controller as Service:

控制器类上的@Route注释也可用于将控制器类分配给服务,以便控制器解析器通过从DI容器中获取控制器来实例化控制器,而不是调用新的PostController()本身:

/**
 * @Route(service="my_post_controller_service")
 */
class PostController
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

service注释中的属性只是告诉Symfony它应该使用指定的服务,而不是使用new语句实例化控制器.它不会自行注册服务.

给你的控制器:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @Route(service="test_service")
 */
class TestController
{
    public function myAction()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要将控制器实际注册为具有test_serviceid 的服务:

services:
    test_service:
        class: Test\TestBundle\Controller\TestController
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是您可以通过在服务定义中指定它们来将依赖项注入构造函数中,而不需要扩展基Controller类.

请参阅SensioFrameworkExtraBundle中的如何将控制器定义为服务Controller作为服务.