eonx-com/easy-notification

EonX 通知服务中的通知派发客户端

6.0.0 2024-08-15 12:18 UTC

This package is auto-updated.

Last update: 2024-09-19 04:49:18 UTC


README

---eonx_docs--- 标题:简介 重量:0 ---eonx_docs---

此包旨在简化 EonX 通知服务内通知的派发,并且仅与此服务兼容。

依赖包(Composer)

安装此包的推荐方法是使用 Composer

$ composer require eonx-com/easy-notification

配置

为了使用 EonX 通知服务发送通知,您需要在服务中注册一个提供者。一旦创建提供者,请设置提供者注册的 API URL,并保留提供者 API 密钥和外部 ID,因为它们将用于发送消息。

请参阅您选择的框架的配置部分。(即将推出...)


CacheConfigFinder

此包将自动向 EonX 通知服务发送 API 请求以获取您的 ApiKey 和提供者的配置。这将确保您的应用程序具有最新的配置,但是,由于配置不经常更改,因此可以轻松地将此配置缓存。

这就是为什么此包为您提供了 EonX\EasyNotification\Config\CacheConfigFinder,以便装饰默认的配置查找服务并缓存找到的配置。

EonX\EasyNotification\Config\CacheConfigFinder 实现依赖于 Symfony 缓存组件,因此请确保它在您的项目中已安装。

请参阅您选择的框架中如何覆盖配置缓存的说明。


用法

配置完成后,此包将从 EonX 通知服务获取所需的配置,并将 EonX\EasyNotification\Client\NotificationClientInterface 服务注册到您的 DI 容器中。然后,您可以将此客户端注入到自己的类中并发送通知。

// src/Listener/UserCreatedListener.php

namespace App\Listener;

use App\Entity\User;
use EonX\EasyNotification\Client\NotificationClientInterface;
use EonX\EasyNotification\Message\RealTimeMessage;
use EonX\EasyNotification\Provider\ConfigProviderInterface;

final class UserCreatedListener
{
    /**
     * @var \EonX\EasyNotification\Provider\ConfigProviderInterface
     */
    private $configFinder;

    /**
     * @var \EonX\EasyNotification\Client\NotificationClientInterface
     */
    private $client;

    public function __construct(ConfigProviderInterface $configFinder, NotificationClientInterface $client)
    {
        $this->configFinder = $configFinder;
        $this->client = $client;
    }

    public function created(User $user): void
    {
        /**
         * In real use case, those values should come from configuration.
         *
         * For multi-tenancies application, it is a best practice to store those values against each tenancy.
         */
        $config = $this->configFinder->provide('my-api-key', 'my-provider-external-id');

        /**
         * Topics are "channels" to send notifications to.
         * Every clients subscribing to any of the topics will then receive the notification.
         */
        $topics = [$user->getExternalId()]; // Good practice is to have 1 topic per user

        /**
         * Body is the notification contents each client will receive.
         * Its structure is completely up to the application but should negotiated with subscribers.
         */
        $body = [
            'title' => 'Welcome!',
            'body' => \sprintf('We are to have you onboard %s', $user->getUsername()),
        ];

        $this->client
             ->withConfig($config) // Set config for next send
             ->send(RealTimeMessage::create($body, $topics)); // Send real time message
    }
}