You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony 4无法自动装配Mailer、Router?依赖注入遇服务不存在报错

Fixing the "EngineInterface service does not exist" Error in Symfony 4

Hey there! The error you’re seeing happens because Symfony 4 no longer registers the Symfony\Component\Templating\EngineInterface as a default service—the framework shifted toward directly using Twig-specific services instead of the generic templating interface. Let’s walk through two ways to fix this:

Symfony 4 recommends injecting Twig's concrete services directly, which is more explicit and aligns with the framework’s modern practices. You have two solid choices here:

A. Inject Twig\Environment

This is the core Twig service that powers template rendering. Update your constructor like this:

use Swift_Mailer;
use Twig\Environment;
use Symfony\Component\Routing\RouterInterface;

public function __construct(Swift_Mailer $mailer, Environment $twig, RouterInterface $router) {
    $this->mailer = $mailer;
    $this->router = $router;
    $this->twig = $twig; // You can keep the property name as $templating if you prefer
}

To render templates, use $this->twig->render('path/to/template.html.twig', $data)—it works exactly like the old EngineInterface method.

B. Inject Symfony\Bridge\Twig\TwigEngine

If you want to stick closer to the original EngineInterface behavior, use Twig’s implementation of that interface:

use Swift_Mailer;
use Symfony\Bridge\Twig\TwigEngine;
use Symfony\Component\Routing\RouterInterface;

public function __construct(Swift_Mailer $mailer, TwigEngine $templating, RouterInterface $router) {
    $this->mailer = $mailer;
    $this->router = $router;
    $this->templating = $templating;
}

This preserves your original property names and template rendering workflow.

Option 2: Register EngineInterface as an Alias (If You Must Keep It)

If you really want to retain EngineInterface in your constructor, manually alias it to Twig’s implementation in your config/services.yaml:

services:
    # Map the interface to the Twig service
    Symfony\Component\Templating\EngineInterface:
        alias: Symfony\Bridge\Twig\TwigEngine

After adding this, Symfony will automatically resolve EngineInterface to the TwigEngine instance when injecting dependencies.

A Quick Note on Auto-Configuration

Since you’re using Symfony 4, as long as your custom service lives in the src/ directory, auto-configuration will handle dependency injection automatically—no need to manually define your service in services.yaml unless you have special settings.

内容的提问来源于stack exchange,提问作者Suraj Gusain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:31:56