codekanzlei/cake-notifications

CakePHP3 通知插件


README

CakePHP 3 Notifications Plugin

Build Status Code Coverage v2-dev License

这是一个 CakePHP 3.8 通知插件,可以通过 cakephp-queuesadilla 任务队列异步发送电子邮件。

要求

安装

1. 使用 composer 安装插件

composer require codekanzlei/cake-notifications

2. 在您的 src/Application.php 中加载插件

$this->addPlugin('Notifications');

3. 配置 config/app.php

在配置文件中设置您的默认区域设置,例如在 app.php 中。此配置是必需的,如果未设置,则会导致异常。

'Notifications' => [
    'defaultLocale' => 'en_US'
]

您还可以覆盖队列选项,如 attemptsattempts_delaydelayexpires_inqueue

'Notifications' => [
    'queueOptions' => [
        'queue' => 'notification'
    ]
]

这不会影响以后使用 queueOptions()。您仍然可以在此处覆盖选项。

此外,请确保设置 cakephp-queuesadilla 插件配置。您可以在以下位置找到示例配置: https://cakephp-queuesadilla.readthedocs.io/en/latest/

或者,您可以在您的引擎文件(vendor/josegonzalez/queuesadilla/src/josegonzalez/Queuesadilla/Engine/*Engine.php)中的 $baseConfig 属性内找到可用的配置选项。

重要:请将 "date.timezone" 在您的 cli/php.ini 中设置为适当的值,否则带有 "delay_until" 的通知可能会在错误的时间发送。

用法

电子邮件

EmailNotification 完全兼容 CakePHP 电子邮件。

将以下内容添加到您想要发送电子邮件的类中

use Notifications\Notification\EmailNotification;

然后简单地创建一个新的 EmailNotification 对象。

$email = new EmailNotification();
$email->to('john.doe@example.com')
    ->setSubject('Send with cake-notifications v2')
    ->send('Hello :)');

您可以使用 CakePHP Email 类提供的所有方法链式调用 https://book.cakephp.com.cn/3.0/en/core-libraries/email.html

此外,以下函数可用

send( array|string|null $content null )

立即发送电子邮件。仍然可用 before- 和 afterSend 回调

setLocale( string|null $locale null )

设置通知的区域设置。如果为 null,则使用 Configure::read('Notifications.defaultLocale')

push()

将电子邮件推送到队列以异步发送

setQueueOptions( array $options null )

您可以从 cakephp-queuesadilla 插件更改一些默认选项。

支持选项

  • attempts 失败后通知将再次执行多少次
  • attempts_delay 通知再次执行需要多长时间(以秒为单位)
  • delay 第一次执行通知需要多长时间(以秒为单位)
  • expires_in 通知将在队列中保持多长时间(以秒为单位)
  • queue 队列名称

setBeforeSendCallback( array|string|null $class null, array $args [] )

将可调用的参数传递给 $class。支持静态和非静态函数。

$email->beforeSendCallback(['Foo', 'bar'], ['first_param', 'second_param'])

这将调用在发送电子邮件之前在 Foo 类中定义的 bar 方法,并传递两个参数。

在发送电子邮件之前操作 EmailNotification 实例,可以返回一个函数,该函数接受通知实例引用并更改配置,例如更改配置文件。然后 bar 方法可能如下所示

public function bar($first_param, $second_param)
{
    // do something
    return function (&$instance) {
        $instance->profile([
            'from' => 'email@example.com'
        ]);
    };
}

setAfterSendCallback( array|string|null $class null, array $args [] )

将可调用的参数传递给 $class。支持静态和非静态函数。

$email-> afterSendCallback(['Foo::bar'], ['first_param', 'second_param'])

这将调用在发送电子邮件之后在 Foo 类中定义的静态 bar 方法,并传递两个参数。

addBeforeSendCallback( array|string|null $class null, array $args [] )

在beforeSend中添加一个额外的回调函数。

addAfterSendCallback( array|string|null $class null, array $args [] )

在afterSend中添加一个额外的回调函数。