srlabs/parley

Laravel的多态消息处理

6.0.0 2022-02-09 04:38 UTC

This package is auto-updated.

Last update: 2024-09-09 10:21:21 UTC


README

Build Status

使用Parley,您可以在Laravel应用程序中轻松地在不同的对象类型之间发送消息。这些“对话”可以是双向的,允许您轻松地与用户就与应用程序相关的话题进行沟通。

  • 将线程与参考对象关联,例如订单或任何其他Eloquent模型实例
  • 跟踪哪些成员已“阅读”或未“阅读”消息
  • 可选地将线程标记为“打开”或“关闭”

以下是一个示例

Parley::discuss([
    'subject' => "A New Game has been added",
    'body'   => "A new game with {$teamB->name} has been added to the schedule.",
    'alias'  => "The Commissioner",
    'author' => $admin,
    'regarding' => $game
])->withParticipant($teamA);

当玩家登录时,可以像这样检索他们的未读Parley消息

$messages = Parley::gatherFor([$user, $user->team])->unread()->get();

如果此用户想回复一条消息,可以这样做

$thread = Parley::find(1);
$thread->reply([
    'body' => 'Thanks for the heads up! We will bring snacks.',
    'author' => $user
]);

更多的使用示例和API可以在这里找到。

安装

此包可以使用composer安装

$ composer require srlabs/parley

将服务提供者和别名添加到您的config/app.php文件中

'providers' => array(
    // ...
    Parley\ParleyServiceProvider::class,
    // ...
)
'aliases' => [
    // ...
    'Parley'    => Parley\Facades\Parley::class,
    // ...
],

接下来,发布并运行迁移

php artisan vendor:publish --provider="Parley\ParleyServiceProvider" --tag="migrations"
php artisan migrate

任何实现Parley\Contracts\ParleyableInterface的Eloquent模型都可以用于发送或接收Parley消息。为了满足此合约,您需要在该模型上提供getParleyAliasAttributegetParleyIdAttribute方法

  • getParleyAliasAttribute() - 指定参与Parley对话的模型的“显示名称”。对于用户来说,这可能就是他们的用户名,或者他们的名字和姓氏的组合。
  • getParleyIdAttribute() - 指定您想要在Parley数据库表中代表此模型的整数ID。您很可能会在这里使用模型的id属性,但这并不总是如此。

注意:虽然您必须为每个Parleyable模型提供别名,但在创建线程时,您不必使用该别名 - 在创建消息时,您可以可选地指定不同的“别名”属性。

您现在可以开始了!

事件

每当创建一个新的线程或添加一条新的回复消息时,都会触发一个事件。您可以在EventServiceProvider中设置您的监听器,如下所示

protected $listen = [
    'Parley\Events\ParleyThreadCreated' => [
        'App\Listeners\FirstEventListener',
        'App\Listeners\SecondEventListener'
    ],
    'Parley\Events\ParleyMessageAdded' => [
        'App\Listeners\ThirdEventListener',
        'App\Listeners\FourthEventListener'
    ],
]

每个事件都传递了线程对象和当前消息的作者。您可以使用getThread()getAuthor方法检索这些对象

class AppEventListener
{

    /**
     * Handle the event.
     *
     * @param  SiteEvent  $event
     * @return void
     */
    public function handle(ParleyEvent $event)
    {
        // Fetch the thread
        $thread = $event->getThread();

        // Fetch the author
        $author = $event->getAuthor();

        // ...
    }
}