在Symfony中创建一个邮件服务


Create an email service in Symfony

我尝试在Symfony Sonata bundle中创建一个服务,以便在创建订单后立即向特定人员发送电子邮件。收到电子邮件的人是用户选择批准订单的人。

我尝试遵循Symfony网站上的服务容器文档,但它对我来说太不完整了。我想看到一个完整的例子,而不仅仅是一些片段。

这是目前为止我的邮件服务类;

<?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;
    }
}

我的服务中的我的服务。

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

当我在控制器操作中调用服务时,我使用这一行;

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

注意:未定义属性:气Bss ' FrontendBundle '控制器' ' PmodOrderController:: $ serviceContainer

就像我之前说的,我看了服务容器的文档,但是我看不懂。

有人能帮我一个完整的例子来解释一切吗?

你不需要在你的服务类中使用setServiceContainer方法,你应该让__construct接受mailer作为第一个参数:

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