Jack Coolen Jack Coolen - 3 months ago 21
PHP Question

Create a email service in Symfony

I try to make a service in my Symfony Sonata bundle to send an email to a specific person as soon as an order is created. The person to whom the email is send is the person the user select to approve the order.

I try to follow the service container documentation on Symfony's website, but it feels too incomplete for me. I want to see a complete example and not just a few snippets.

This is my email service class so far;

<?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 looks like this;

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





And when I call the service in a controller action I use this line;

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





The error I'm getting state;


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


Like I said before, I've looked at the service container documentation but I can't understand it.

Can someone please help me with a nice full example explaining everything?

Answer

You don't need setServiceContainer method in your service class, instead of it you should have __construct accepting mailer as first argument:

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);
    }
}
Comments