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

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

问题描述

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

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.

我想念什么?

推荐答案

来自

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

/**
 * @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天全站免登陆