根据文档,我应该能够将implementedEvents直接添加到我的mailer中,以将我的所有邮件逻辑与代码分离。
然而,当我遵循文档中的确切示例时;我发现我实现的事件功能不起作用。(不发送电子邮件和不记录任何内容)
我应该在某个地方实现我的电子邮件程序类吗?如果是,我应该如何注册我的电子邮件课程?
这是我的邮件类:
<?php
namespace App'Mailer;
use Cake'Mailer'Mailer;
use Cake'Log'Log;
/**
* Purchase mailer.
*/
class PurchaseMailer extends Mailer
{
/**
* Mailer's name.
*
* @var string
*/
static public $name = 'Purchase';
public function implementedEvents()
{
return [
'Model.afterSave' => 'onStatusChange'
];
}
public function onStatusChange(Event $event, EntityInterface $entity, ArrayObject $options)
{
Log::write(
'info',
'd1'
);
//if ($entity->isNew()) {
$this->send('sendStatusChangeMails', [$entity]);
//}
}
/**
* @param EntityInterface $entity
* @return [type]
*/
public function sendStatusChangeMails($entity)
{
Log::write(
'info',
'd2'
);
//if($entity->status_id == 1) {
//@todo email???
$this
->template('purchase')
->layout('default')
->emailFormat('html')
->from(['info@example.com' => 'TEST'])
->to('test@test.com')
->subject('test')
->set(['content' => 'this is a purhcase testing mail.']);
//}
}
}
答案是Mailer类和事件文档。
https://api.cakephp.org/3.2/class-Cake.Mailer.Mailer.html
https://book.cakephp.org/3.0/en/core-libraries/events.html#registering-监听器
我们的mailer可以在应用程序引导程序中注册,也可以在Table类的initialize()钩子中注册。
所以你可以在你的用户中订阅你的邮件表初始化:
public function initialize(array $config)
{
parent::initialize($config);
$mailer = new UserMailer(); //use App'Mailer'UserMailer;
$this->eventManager()->on($mailer);
//more code...
}