问题
According to documentation , I should be able to add implementedEvents directly to my mailer to seperate all my mailing logic from my codes.
However, when I follow the exact examples in documentation; I see my implemented event function does not work. (not sending emails & does not log anything)
Should I implement my emailer class to somewhere? If so, how should I register my emailer class?
This is my mailer class:
<?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.']);
//}
}
}
回答1:
Answer is the Mailer Class and Events docs.
https://api.cakephp.org/3.2/class-Cake.Mailer.Mailer.html
https://book.cakephp.org/3.0/en/core-libraries/events.html#registering-listeners
Our mailer could either be registered in the application bootstrap, or in the Table class' initialize() hook.
So you could subscribe in your mail in your UsersTable initialize:
public function initialize(array $config)
{
parent::initialize($config);
$mailer = new UserMailer(); //use App\Mailer\UserMailer;
$this->eventManager()->on($mailer);
//more code...
}
来源:https://stackoverflow.com/questions/36404397/cakephp-3-implementedevents-does-not-fire-in-emailer