Skip to content
Advertisement

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

I try to attach a file via Swiftmail to my Email in Symfony:

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

The problem is now, that because of the :: Symfony thinks that I am trying to load a service. The error message is:

Attempted to load class “Swift_Attachment” from namespace “AppService”. Did you forget a “use” statement for another namespace?

How can I prevent this?

Advertisement

Answer

Nothing to do with symfony and services. do Swift_Attachment (backslash at the begining) like you do new Swift_Message because the class is in global scope. Right now php tries to find the class in current namespace which happens to be AppService (check top of the file this code is from to verify).

Symfony never loads services via static methods (no magic there, you have to access them from DIC or inject them to your service as dependency).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement