Create an Email Service in Symfony

I am trying to make a service in my Symfony Sonata package to send an email to a specific person as soon as an order is created. The person to whom the email is sent is the person that the user selects to confirm the order.

I am trying to execute container service documentation on the Symfony website , but for me this is too incomplete. I want to see a complete example, not just a few snippets.

This is my email service class,

<?php

namespace Qi\Bss\BaseBundle\Lib\PurchaseModule;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Doctrine\ORM\EntityManager;

/**
 * 
 */
class Notifier 
{
    /**
     * Service container
     * @var type 
     */
    private $serviceContainer;


    public function notifier($subject, $from, $to, $body) {
        $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom($from)
            ->setTo($to)
            ->setBody($body)
        ;
        $this->serviceContainer->get('mailer')->send($message);
    }

    /**
     * Sets the sales order exporter object
     * @param type $serviceContainer
     */
    public function setServiceContainer($serviceContainer)
    {
        $this->serviceContainer = $serviceContainer;
    }
}

My service inside my services.yml file is as follows:

bss.pmod.order_notifier:
    class: Qi\Bss\BaseBundle\Lib\PurchaseModule\Notifier
    arguments: ["@mailer"]

And when I call the service in the controller action, I use this line:

$this->get('bss.pmod.order_notifier')->notifier();

The error I get is

: Undefined : Qi\Bss\FrontendBundle\Controller\PmodOrderController:: $serviceContainer

, , .

-, , , ?

+4
1

setServiceContainer , __construct :

class Notifier 
{
    protected $mailer;

    public function __construct($mailer)
    {
        $this->mailer = $mailer;
    }

    public function notifier() {
        $message = \Swift_Message::newInstance()
            ->setSubject('Simon Koning')
            ->setFrom('noreply@solcon.nl')
            ->setTo('simon@simonkoning.co.za')
            ->setBody('The quick brown fox jumps over the lazy dog.')
        ;
        $this->mailer->send($message);
    }
}
+3

Source: https://habr.com/ru/post/1650918/