这似乎是将 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 services和 Controller as Service in SensioFrameworkExtraBundle .
关于symfony - 如何使用注释将 Controller 定义为服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31366074/