如何在Symfony 2中使用控制器作为@Route注释的服务?

时间:2014-12-01 13:06:14

标签: symfony routing annotations

我是一个配置为服务的控制器。我想使用@Route注释来定义路线。

当我尝试访问路线时,我得到:

ContextErrorException: Catchable Fatal Error: Argument 1 passed to Galexis\RequestDispatcherBundle\Controller\RequestDispatcherController::__construct() must implement interface Psr\Log\LoggerInterface, none given, called in /Users/ugxnbpluse/development/git/integrationPHP/symfony2/app/cache/dev/classes.php on line 2282 and defined in /Users/ugxnbpluse/development/git/integrationPHP/symfony2/src/Galexis/RequestDispatcherBundle/Controller/RequestDispatcherController.php line 29 

从我理解的错误消息中,symfony不知道它不应该为控制器调用new,而是从DI容器中取出它。

symfony docs(最后一部分)告诉我添加类似

的内容
@Route(service="my_post_controller_service")

但是它认为symfony并不真正支持服务属性:

BadMethodCallException: Unknown property 'service' on annotation 'Symfony\Component\Routing\Annotation\Route'.

有什么想法吗?

控制器:

class RequestDispatcherController
{
    // ... 

    public function __construct(
        LoggerInterface $logger,
        RequestDispatcherService $requestDispatcherService)
    {
        $this->logger = $logger;
        $this->requestDispatcherService = $requestDispatcherService;
    }

    /**
     * @Route("requestDispatcher/{applicationName}")
     * @return Response
     */
    public function dispatch(Request $request)
    {
        // ... 
    }
}

的routing.yml:

_request_dispatcher:
    resource: "@FooRequestDispatcherBundle/Controller/RequestDispatcherController.php"
    type:     annotation

service.yml:

parameters:
    request_dispatcher.class:                 Foo\RequestDispatcherBundle\Service\RequestDispatcherService
    request_dispatcher_controller.class:      Foo\RequestDispatcherBundle\Controller\RequestDispatcherController

services:
    request_dispatcher_service:
        class:        "%request_dispatcher.class%"
        arguments:    ["@foo.integration.application", "@buzz.multi.client" ]

    request_dispatcher_controller:
        class:        "%request_dispatcher_controller.class%"
        arguments:    ["@logger", "@request_dispatcher_service"]

1 个答案:

答案 0 :(得分:3)

我认为您应该使用use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;代替use Symfony\Component\Routing\Annotation\Route;