门户允许您轻松地在多个应用程序间分发Laravel事件。

0.2.1 2020-07-02 20:31 UTC

This package is not auto-updated.

Last update: 2023-09-30 23:41:47 UTC


README

68747470733a2f2f692e696d6775722e636f6d2f624a797a644f662e706e67

Build Status Total Downloads Latest Stable Version License

介绍

门户允许您轻松地在多个应用程序间分发Laravel事件。

安装

要开始使用门户,只需运行

composer require footage-firm/portal

如果使用Laravel 5.5+,则无需手动注册服务提供程序。但是,如果您使用的是Laravel的早期版本,请在您的app配置文件中注册PortalServiceProvider

'providers' => [
    // Other service providers...

    Storyblocks\Portal\PortalServiceProvider::class,
],

需要安装此包的所有项目,以便能够发送或接收事件

工作原理

所有与门户连接的Laravel应用程序都需要使用中央队列来传输事件,因此请确保已配置队列,并且所有连接的Laravel应用程序都在使用相同的队列。

配置队列

警告:在继续之前,请确保您的默认QUEUE_DRIVERconfig/queue.php中未设置为sync,因为这将导致传送事件无限循环

接收事件的每个应用程序都需要配置队列和队列工作者,以便监听门户事件。

如果您使用的是默认Laravel队列系统,可以通过运行带有--queue参数的工作者来完成,如下所示

php artisan queue:work redis --queue=portal-myapp

如果您使用Laravel Horizon,只需更新环境配置,向数组中添加另一个队列,如下所示

'environments' => [
    'production' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['default', 'portal-myapp'],
            'balance' => 'simple',
            'processes' => 10,
            'tries' => 3,
        ],
    ],
    ...

注意:队列名称需要始终以portal-前缀开始

配置事件目标

当触发传送资格事件时,将执行自定义处理程序。此处理程序负责返回事件发送到的目标。

此回调可以在任何您喜欢的地方进行配置,但一个不错的起点是您的AppServiceProvider中的boot()函数

这里有一些示例

// Teleport events to a static list of apps
Portal::setTeleportationTargetsHandler(function ($eventName) {
    return [
        'myapp' // Note: This is the same name as specified in the queue worker above (but without the "portal-" prefix)
    ];
});

// Teleport events to a database-defined list of targets
Portal::setTeleportationTargetsHandler(function ($eventName) {
    return Server::where('is_active', 1)
        ->where('hostname', '!=', gethostname()) // Exclude ourselves
        ->lists('hostname');
});

// Send certain events to certain targets
Portal::setTeleportationTargetsHandler(function ($eventName) {
    if ($eventName === 'SpecialEvent') {
        return [
            'myapp',
            'specialapp'
        ];
    } else {
        return [
            'myapp';
        ];
    }
});

基本用法

发送门户事件

像往常一样创建您的Laravel事件,但请确保实现ShouldTeleport接口。

示例

<?php

namespace App\Events;

use Storyblocks\Portal\ShouldTeleport;

class OrderShipped implements ShouldTeleport
{
}

事件可以像往常一样触发

event(new OrderShipped());

事件将自动排队并传送至任何其他启用了门户的Laravel应用程序。

接收门户事件

只需在EventServiceProvider中定义一个事件监听器,就像您通常在Laravel应用程序中做的那样。

示例

protected $listen = [
    'App\Events\OrderShipped' => [
        'App\Listeners\SendShipmentNotification',
    ],
];

许可证

门户是开源软件,许可协议为MIT许可