【问题标题】:Symfony controller with URL parameters and injected services带有 URL 参数和注入服务的 Symfony 控制器
【发布时间】:2019-06-18 17:02:28
【问题描述】:

在 Symfony 3.4 中,我有一个控制器,它有一些从 URL 填充的参数,而且我需要注入一个服务。我收到以下错误消息:

控制器 “Acs\EventNodeBundle\Controller\MainController::calendarAction()” 要求您为“$router”参数提供一个值。任何一个 该参数是可空的,并且没有提供空值,没有 已提供默认值或因为存在非可选 这之后的争论。

为什么 Symfony 不注入路由器?这是我的代码:

控制器:

...

use Symfony\Bundle\FrameworkBundle\Routing\Router;

/**
 * Class MainController
 */
class MainController extends Controller
{
    /**
     * @param Router   $router
     * @param null|int $year
     * @param null|int $month
     * @return RedirectResponse|Response
     */
    public function calendarAction(Router $router, $year = null, $month = null)
    {
...

services.yml:

...
services:
    # default configuration for services in *this* file
    _defaults:
        # automatically injects dependencies in services
        autowire: true
        # automatically registers services as commands, event subscribers, etc.
        autoconfigure: true
        # services cannot be fetched directly from the container via $container->get()
        # need to override this setting individually
        public: false

        bind:
            $entityManager: '@Doctrine\ORM\EntityManagerInterface'

   # enable autowiring for controllers
   Acs\EventNodeBundle\Controller\:
       resource: '../../Controller'
       public: true
       tags: ['controller.service_arguments']
...

还有路由:

...
    eventnode_main:
        path: /{year}/{month}
        methods: [GET]
        defaults: { _controller: AcsEventNodeBundle:Main:calendar, year: null, month: null}
        requirements:
            year: '\d+'
            month: '\d+'
...

【问题讨论】:

    标签: symfony controller


    【解决方案1】:

    控制器中的构造函数应该可以完成这项工作:

    /**
     * MainController constructor.
     *
     * @param Router $router
     */
    public function __construct(
        Router $router
    ) {
        $this->router = $router;
    }
    

    【讨论】:

    • 这解决了问题,谢谢。只是为了记录,这是由于我尝试将服务和 URL 参数同时注入控制器方法而引起的吗?因为在另一个不使用 URL 参数的控制器中,我可以简单地将服务注入控制器方法本身,而不是控制器构造函数。
    • 我认为您也可以在路由参数之后添加服务,如下所述:symfony.com/doc/current/controller.html#fetching-services
    【解决方案2】:

    尝试将其添加到您的 services.yml 中:

    Acs\EventNodeBundle\:
        resource: '../../src/EventNodeBundle/*'
    

    这将使 src/EventNodeBundle 中的类可用作服务。

    请参阅此文档: https://symfony.com/doc/3.4/service_container/3.3-di-changes.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多