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

Symfony 3.3+PHP7.1环境下扩展重复注册报错求助

问题排查与解决方案:Twig扩展重复注册导致的报错

这个报错的核心原因很明确:你的MailerService继承了\Twig_Extension,而Symfony的TwigBundle会自动扫描并注册所有Twig扩展类,但你同时又在services.yml里手动注册了这个类作为服务,这就导致同一个扩展被尝试注册两次,从而抛出"Unable to register extension..."的错误。

为什么本地运行正常?大概率是本地缓存没触发自动发现逻辑,或者开发环境的配置和服务器存在细微差异,但服务器的运行状态才是符合Symfony规范的表现,我们需要修正代码来适配规范。

下面是具体的修复步骤:

1. 移除重复的服务注册

打开你的services.yml,删除手动注册的MailSender服务段,因为Twig会自动处理这个扩展的注册:

# 删掉这段
MailSender: 
  class: AppBundle\Service\MailerService
  arguments: 
    - "@swiftmailer.mailer.default"
    - "@twig"
  public: true

2. 优化依赖注入(避免手动new服务)

你当前在CoreService里手动new MailerService()的做法不符合Symfony的依赖注入最佳实践,而且容易引发问题。我们改成构造注入的方式:

修改CoreService的构造函数

// CoreService.php
namespace AppBundle\Service;

use AppBundle\Entity\Advert;
use AppBundle\Entity\Logs;
use AppBundle\Entity\UserSettings;
use Doctrine\ORM\EntityManager;
use AppBundle\Service\MailerService; // 引入MailerService

class CoreService {
  protected $em;
  protected $mailerService; // 替换原来的mailer和twig属性

  public function __construct(EntityManager $em, MailerService $mailerService) {
    $this->em = $em;
    $this->mailerService = $mailerService; // 注入MailerService
  }

  // ... 其他方法修改 ...
  public function fetch() {
    // ... 省略原有代码 ...
    // 替换原来的new MailerService部分
    $this->mailerService->sendMail("xxx", $emails);
    print("sent emails\n");
    return $emails;
  }

  public function test(){
    print("testuje");
    $emails = $this->em ->getRepository(Advert::class) ->findBy(array('sent' => '0'));
    $this->mailerService->sendMail("xxx", $emails); // 同样修改这里
  }
}

更新CoreService的服务配置

回到services.yml,更新CoreService的参数,改为注入MailerService:

CoreService: 
  class: AppBundle\Service\CoreService
  arguments: 
    - "@doctrine.orm.entity_manager"
    - "@AppBundle\Service\MailerService" # 注入自动注册的MailerService
  public: true

3. 优化控制器的服务调用

控制器里也不要手动new CoreService(),直接通过方法注入获取:

/**
 * @Route("/debug/fetch", name="debug_fetch")
 */
public function debugFetch(CoreService $coreService) {
  $emails = $coreService->fetch();
  return $this->render('email/email.html.twig', array(
    'emails' => $emails,
  ));
}

4. 清理服务器缓存

最后,在服务器上执行Symfony的缓存清理命令,确保配置生效:

php bin/console cache:clear --env=dev

这样修改后,Twig会自动处理MailerService的扩展注册,同时依赖注入会正确管理服务实例,就不会再出现重复注册的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:11:45