如何使用注释将控制器定义为服务? [英] How exactly can I define a controller as service using annotations?

查看:25
本文介绍了如何使用注释将控制器定义为服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This seems to be the fastest and simpliest way to use a controller as service, but I am still missing a step because it doesn't work.

这是我的代码:

控制器/服务:

// 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');
}

当我这样做时,我收到错误

When I do that, I get the error

您请求了一个不存在的服务test_service".

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

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

When I check the list of services with app/console container:debug, I don't see my newly created service.

我错过了什么?

推荐答案

来自 SensioFrameworkExtraBundle 中的控制器即服务:

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

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 语句实例化控制器.它不会自行注册服务.

The service attribute in the annotation is just to tell Symfony it should use the specified service, instead of instantiating the controller with the new statement. It does not register the service on its own.

给你的控制器:

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

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

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

You need to actually register the controller as a service with the test_service id:

services:
    test_service:
        class: Test\TestBundle\Controller\TestController

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

The advantage of this approach is that you can inject your dependencies into the constructor by specifying them in the service definition, and you don't need to extend the base Controller class.

参见如何将控制器定义为服务SensioFrameworkExtraBundle 中的控制器即服务.

这篇关于如何使用注释将控制器定义为服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆