thebeaverhead/cakephp-bulk-notifications

CakePHP 批量通知插件

1.0.2 2020-03-06 10:26 UTC

This package is auto-updated.

Last update: 2024-09-06 21:03:15 UTC


README

此插件允许您创建批量通知。假设您向主题的所有者发送关于主题新评论的电子邮件通知。当用户在一个主题内有5条评论时,用户可能会收到5封电子邮件,这可能会很烦人。

此插件允许为这种情况创建一个队列,并在这些评论的创建日期之间不超过30秒(可配置)的情况下发送一封包含5条新评论的电子邮件。

安装

composer require thebeaverhead/cakephp-bulk-notifications

设置

在您的应用控制台中

bin/cake plugin load BulkNotifications

应用迁移

bin/cake migrations migrate -p BulkNotifications

使用方法

创建要发送的电子邮件(不增加)

$userEntity = TableRegistry::getTableLocator()->get('Users')->get($userId);
$topic = ['title' => 'foo'];
$comments = [
    ['text' => 'foo'], 
    ['text' => 'bar']
];

$bulkNotification = new BulkNotification();
$bulkNotification->add(
    $userEntity,
    'Email subject',
    'email/template/path',
    ['topic' => $topic, 'comments' => $comments],
    ['sendDate' => 1580108540, 'receiverEmailColumn' => 'email']
);

创建要发送的增量电子邮件

$userEntity = TableRegistry::getTableLocator()->get('Users')->get($userId);
$userEntity2 = TableRegistry::getTableLocator()->get('Users')->get($userId2);

$topic = ['title' => 'foo'];
$comments = [
    ['text' => 'foo'], 
    ['text' => 'bar']
];

$bulkNotification = new BulkNotification();
$bulkNotification->addIncrement(
    [$userEntity, $userEntity2],
    'Email increment subject',
    'email/template/path',
    ['topic' => $topic],                    // not incremental data
    ['comments' => $comments],              // incremental data
    ['sendDate' => 1580108540, 'receiverEmailColumn' => 'email']
);


// Increment notification has been created
// in 10 sec new comment has been added to the same topic
sleep(10);
$comments = [
    ['text' => 'baz']
];

$bulkNotification->addIncrement(
    $userEntity,
    'Email increment subject',
    'email/template/path',
    ['topic' => $topic],                    // not incremental data
    ['comments' => $comments]               // incremental data
);

创建 email template.ctp

<?php
/**
 * @var \App\View\AppView $this 
 * @var \App\Model\Entity\User $receiver  // plugin automatically pass UserEntity as $receiver
 * @var array $comments
 * @var \App\Model\Entity\Comment $comment
 * @var \App\Model\Entity\Topic $topic
 */
?>

Hi <?= $receiver['name'] ?>, your topic <?= $topic['title'] ?> has new comment(s):
<ul>
  <?php foreach ($comments as $key => $comment): ?>
    <li>
      Comment #<?= $key ?>
      <?= $comment['text'] ?>
    </li>
  <?php endforeach; ?>
</ul>

要发送通知,请运行

bin/cake BulkNotifications run

实际上您需要将此命令添加到 crontab 中。

配置

两种方法 addaddIncrement 都支持 $options 参数

$options = [
 'sendDate' => 1580108540,         // (null by default) if this date isn't reached notification won't be sent
 'receiverEmailColumn' => 'email'  // (`email` by default) email column in the receiver entity
];

Shell BulkNotifications 支持 BulkNotifications.send_delay 配置(默认为 30 秒)如果之前的通知是在不到30秒前创建或更新的,则不会发送增量电子邮件。

在 config/app.php 中您可以添加

'BulkNotifications' => [
  'send_delay' => 60
],