具有URL参数和注入服务的Symfony控制器

时间:2019-06-18 07:30:37

标签: symfony controller

在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+'
...

2 个答案:

答案 0 :(得分:1)

您的Controller中的构造函数应执行以下操作:

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

答案 1 :(得分:0)

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

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

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

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