symfony - 如何使用注释将 Controller 定义为服务?

标签 symfony service annotations

这似乎是将 Controller 用作服务的最快和最简单的方法,但我仍然缺少一步,因为它不起作用。

这是我的代码:

Controller /服务:

// 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
}

采用 :
// Test\TestBundle\Controller\UseController.php

// ...
public function useAction() {
  $testService = $this->get('test_service');
}

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

You have requested a non-existent service "test_service".



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

我错过了什么?

最佳答案

来自 Controller as Service in SensioFrameworkExtraBundle :

The @Route annotation on a controller class can also be used to assign the controller class to a service so that the controller resolver will instantiate the controller by fetching it from the DI container instead of calling new PostController() itself:

/**
 * @Route(service="my_post_controller_service")
 */
class PostController
{
    // ...
}

service注释中的属性只是告诉 Symfony 它应该使用指定的服务,而不是用 new 实例化 Controller 。陈述。它不会自行注册服务。

给定您的 Controller :

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

/**
 * @Route(service="test_service")
 */
class TestController
{
    public function myAction()
    {
    }
}

您需要使用 test_service 将 Controller 实际注册为服务。 ID:
services:
    test_service:
        class: Test\TestBundle\Controller\TestController

这种方法的优点是您可以通过在服务定义中指定它们来将依赖项注入(inject)到构造函数中,并且您不需要扩展基础 Controller类(class)。

How to define controllers as servicesController as Service in SensioFrameworkExtraBundle .

关于symfony - 如何使用注释将 Controller 定义为服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31366074/

相关文章:

php - 为 Doctrine 问题设置 utf8 字符集

networking - 无法通过指定端点的 Kubernetes 服务访问服务

java - Spring的@Value注释是国际化的一部分吗?

linux - 防止在 Redhat 7 中停止 auditd 服务

android:在发送到服务或广播接收器的启动器中创建快捷方式

java - 如何获取注释参数的值以供在 AspectJ 中使用?

java - Hibernate 没有在 pojo 的父类中获取继承属性

mysql - Doctrine2/Symfony2 - 每个包使用不同的数据库

symfony - 如何在parameters.yml symfony2中转义 "%"

mongodb - 绑定(bind)学说ORM实体和学说ODM文档,在SonataAdminBundle中使用