Symfony 3 SwiftMailer as a Service

3.6k Views Asked by At

What am I missing?

services.yml

AppBundle\Services\ItemAddService:
   arguments: ['@mailer']

ItemAddService class

namespace AppBundle\Services;

class ItemAddService{

private $mymailer;

public function __construct(\Swift_Mailer $mailer){

    $this->mymailer = $mailer;

}

public function itemCreatedMailer(){

    $message = (new \Swift_Message('Hello Email'))
        ->setFrom('[email protected]')
        ->setTo('[email protected]')
        ->setBody("Successfully got SwiftMailer to mail from Symfony3");

    $this->mymailer->send($message);

    return "Check mail";

}
}

When I call itemCreateMailer() in the controller I get this

"Type error: Argument 1 passed to AppBundle\Services\ItemAddService::__construct() must be an instance of SwiftMailer, none given, called in /home/admin-daniel/symfony-test-sites/july132017/src/AppBundle/Controller/DefaultController.php"

Missing something....

2

There are 2 best solutions below

5
On

You don't need a use because you're using "\" before the class name that's mean the full class name . Have a Look to my services file https://github.com/ismail1432/eniams-website/blob/master/app/config/services.yml . After that in your Controller call the service via the id which is app.send_mail but you name it as you want . So in the Controller do that $this->get('app_send_mail')->itemCreatedMailer();

1
On

Try this in services.yml

AppBundle\Services\ItemAddService: arguments: $mailer: '@mailer'