我尝试在我的Symfony Sonata软件包中提供服务,以便在创建订单后立即向特定人员发送电子邮件.发送电子邮件的人是用户选择批准订单的人.
我尝试按照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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的services.yml文件中的服务看起来像这样;
bss.pmod.order_notifier:
class: Qi\Bss\BaseBundle\Lib\PurchaseModule\Notifier
arguments: ["@mailer"]
Run Code Online (Sandbox Code Playgroud)
当我在控制器动作中调用服务时,我使用这一行;
$this->get('bss.pmod.order_notifier')->notifier();
Run Code Online (Sandbox Code Playgroud)
错误我得到了状态;
注意:未定义属性:Qi\Bss\FrontendBundle\Controller\PmodOrderController :: $ serviceContainer
就像我之前说过的那样,我查看了服务容器文档,但我无法理解它.
有人可以帮我一个很好的完整例子来解释一切吗?
您的服务类中不需要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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
669 次 |
| 最近记录: |