如何防止 Symfony 在使用 Swift 邮件附件时尝试加载服务?

How can I prevent Symfony trying to load a service while using Swift Mailer Attachment?

我尝试通过 Swiftmail 将文件附加到我在 Symfony 中的电子邮件:

$message = (new \Swift_Message($message))
      ->setFrom([$smtpMail => $smtpName])
      ->setTo($smtpMail)
      ->setBody($html, 'text/html');
      ->attach(Swift_Attachment::fromPath('sample.pdf'));

现在的问题是,由于 :: Symfony 认为我正在尝试加载服务。 错误信息是:

Attempted to load class "Swift_Attachment" from namespace "App\Service". Did you forget a "use" statement for another namespace?

我该如何防止这种情况发生?

与 symfony 和服务无关。像 new \Swift_Message 一样做 \Swift_Attachment(开头的反斜杠),因为 class 在全局范围内。 现在 php 试图在当前命名空间中找到 class,恰好是 App\Service(检查此代码来自的文件顶部以进行验证)。

Symfony 从不通过静态方法加载服务(那里没有魔法,您必须从 DIC 访问它们或将它们作为依赖注入到您的服务中)。