dongren9966 2018-11-01 21:16
浏览 98

如何使用Abstract类在Symfony中自动装配公共控制器依赖项

I have created an abstract BaseController class that extends AbstractController. This is so that all the Common Dependencies don't have to be injected in each Controller class that I have (e.g. EntityManager and RequestStack).

However, I have some Controller classes where I would like to inject additional services in the constructor, but this is causing problems.

// src/Controller/BaseController.php
namespace App\Controller;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RequestStack;

abstract class BaseController extends AbstractController
{
    protected $em;
    protected $request;

    public function __construct(EntityManagerInterface $em, RequestStack $request)
    {
        $this->em = $em;
        $this->request = $request->getCurrentRequest();
    }
}

I can then just extend my Controller classes and call for example $this->em in any of the methods.

However, let's say that I wanted to do the following:

// src/Controller/DashboardController.php
namespace App\Controller;

use Symfony\Component\Translation\TranslatorInterface;

class DashboardController extends BaseController
{
    public function __construct(TranslatorInterface $translator)
    {
        parent::__construct();
        $this->translator = $translator;
    }

    public function index()
    {
        // use $this->translator()
    }
}

This would cause an error as the constructor of the BaseController is expecting two arguments to be passed. I've tried adding the following to my services.yaml but to no avail:

App\Controller\BaseController:
        arguments: ['@doctrine.orm.entity_manager', '@request_stack']

What would be the best way to autowire these arguments, and would this be a good practice?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 wireshark抓不到vlan
    • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
    • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
    • ¥15 stata安慰剂检验作图但是真实值不出现在图上
    • ¥15 c程序不知道为什么得不到结果
    • ¥40 复杂的限制性的商函数处理
    • ¥15 程序不包含适用于入口点的静态Main方法
    • ¥15 素材场景中光线烘焙后灯光失效
    • ¥15 请教一下各位,为什么我这个没有实现模拟点击
    • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来