Search code examples
phpsymfonyoopswiftmailer

How to properly call a function with instance in Symfony 4


I'm trying to send an email with SMTP in Symfony 4 and I have the following function as per the docs.

public function send_smtp(\Swift_Mailer $mailer)
{
    $message = (new \Swift_Message('Hello Email'))
        ->setFrom('[email protected]')
        ->setTo('[email protected]')
        ->setBody('test email content');
    $mailer->send($message);
}

However, I want to call this function from a different one like

$this->send_smtp();

But it complains about 'No parameters are passed' and

$this->send_smtp(\Swift_Mailer);

also gives the error message

Undefined constant 'Swift_Mailer'

What can be the problem and how could it be solved?


Solution

  • There are a few solutions possible. You can add the parameter with typehinting in your action and then use it to call your function:

    /**
     * @Route("/something")
     */
    public function something(\Swift_Mailer $mailer)
    {
        $this->send_smtp($mailer);
    }
    

    or you can retrieve the service from the container in the send_smtp function:

    public function send_smtp()
    {
        $mailer = $this->get('mailer');
    
        $message = (new \Swift_Message('Hello Email'))
            ->setFrom('[email protected]')
            ->setTo('[email protected]')
            ->setBody('test email content');
    
        $mailer->send($message);
    
    }