CakePhp:Cake Email AfterSend 事件

CakePhp: Cake Email AfterSend event

每天早上好body,

我目前正在使用 CakePHP。
我想在 CakePHP 发送电子邮件后设置一个事件,因为我想在数据库中存储这封电子邮件的日志,其中包含发件人、收件人、主题和 body.
目前我正在使用本机日志系统(所有 headers 和 body 的电子邮件都在同一个地方),但变得太乱而无法调试。

CakeEmail class 不提供回调方法,如果不编辑 CakeEmail class。
,我找不到任何调用此类事件的方法 当然,我可以创建一个扩展原生 CakeEmail class 的 MyCakeEmail class,但这意味着每个 new CakeEmail() 还在代码中。

你有什么建议?
非常感谢!

(抱歉英语不好,不是我的母语)

使用自定义记录器:

Implement your own logger with the DB features you want and configure it in bootstrap for the email scope which is the default scope for email logs or change the whole logging in the config of the email class. See this part of the email class.

1161:         $contents = $this->transportClass()->send($this);
1162:         if (!empty($this->_config['log'])) {
1163:             $config = array(
1164:                 'level' => LOG_DEBUG,
1165:                 'scope' => 'email'
1166:             );
1167:             if ($this->_config['log'] !== true) {
1168:                 if (!is_array($this->_config['log'])) {
1169:                     $this->_config['log'] = array('level' => $this->_config['log']);
1170:                 }
1171:                 $config = $this->_config['log'] + $config;
1172:             }
1173:             CakeLog::write(
1174:                 $config['level'],
1175:                 PHP_EOL . $contents['headers'] . PHP_EOL . $contents['message'],
1176:                 $config['scope']
1177:             );
1178:         }

使用你自己的 class - 但要正确

Of course I can create a MyCakeEmail class that extends the native CakeEmail class, but this means changing every new CakeEmail() yet in the code.

好吧,您可以使用自己的电子邮件 class。但是在代码中到处做 new SomeClass() 在任何情况下恕我直言都不是一件好事。你刚刚知道为什么。不进行这种易于测试的另一个原因。

而是在继承链(AppController、AppModel...)上层的某些 class 中执行此操作:

public function getEmailInstance($config = null) {
    return new MyEmailClass($config);
}

这允许您简单地更改 class "globally" 并在测试中模拟该方法。

如果您使用的是 php 5.4(或 5.5,现在不确定),您也可以为此使用一个特征,并且仅在需要该功能的 class 中使用它。