定制 mvanduijker/laravel-mercure-broadcaster 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mvanduijker/laravel-mercure-broadcaster

Composer 安装命令:

composer require mvanduijker/laravel-mercure-broadcaster

包简介

Mercure broadcaster

README 文档

README

Latest Version on Packagist Build status Total Downloads

Laravel broadcaster for Mercure for doing Server Sent Events in a breeze.

Installation

Make sure you have installed Mercure and have it running. Check their docs how to do it. (It's pretty easy)

Install the package via Composer:

composer require mvanduijker/laravel-mercure-broadcaster

Configure laravel to use the Mercure broadcaster by editing config/broadcasting.php for example:

<?php

return [

    'default' => env('BROADCAST_DRIVER', 'mercure'),

    'connections' => [

        // ...

        'mercure' => [
            'driver' => 'mercure',
            'url' => env('MERCURE_URL', 'http://localhost:3000/.well-known/mercure'),
            'secret' => env('MERCURE_SECRET', 'aVerySecretKey'),
        ],

    ],

];

Usage

Add an event which implements ShouldBroadcast interface like in https://laravel.com/docs/master/broadcasting#defining-broadcast-events

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewsItemCreated implements ShouldBroadcast
{
    /**
     * @var NewsItem
     */
    public $newsItem;

    public function __construct(NewsItem $newsItem)
    {
        $this->newsItem = $newsItem;
    }

    public function broadcastOn()
    {
        return new Channel('http://example/news-items');
    }
}

In your frontend do something like:

var es = new EventSource('http://localhost:3000/.well-known/mercure?topic=' + encodeURIComponent('http://example/news-items'));
es.addEventListener('message', (messageEvent) => {
    var eventData = JSON.parse(messageEvent.data);
    console.log(eventData);
});

Private channels go a bit differently than with broadcasting through sockets. Private channels are baked in Mercure and are secured with a jwt token.

First create a http middleware, so we can generate the Mercure authentication cookie with the token. Don't forget to add the middleware to your route!

Example:

<?php 

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cookie;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;

class MercureBroadcasterAuthorizationCookie
{
    public function handle(Request $request, Closure $next)
    {
        /** @var Response $response */
        $response = $next($request);

        if (!method_exists($response, 'withCookie')) {
            return $response;
        }

        return $response->withCookie($this->createCookie($request->user(), $request->secure()));
    }

    private function createCookie($user, bool $secure)
    {
        // Add topic(s) this user has access to
        // This can also be URI Templates (to match several topics), or * (to match all topics)
        $subscriptions = [
            "http://example/user/{$user->id}/direct-messages",
        ];

        $jwtConfiguration = Configuration::forSymmetricSigner(
            new Sha256(),
            InMemory::plainText(config('broadcasting.connections.mercure.secret'))
        );

        $token = $jwtConfiguration->builder()
            ->withClaim('mercure', ['subscribe' => $subscriptions])
            ->getToken($jwtConfiguration->signer(), $jwtConfiguration->signingKey())
            ->toString();

        return Cookie::make(
            'mercureAuthorization',
            $token,
            15,
            '/.well-known/mercure', // or which path you have mercure running
            parse_url(config('app.url'), PHP_URL_HOST),
            $secure,
            true
        );
    }
}

Because Laravel encrypts and decrypts cookies by default, don't forget to add an exception for the mercureAuthorization cookie in App\Http\Middleware\EncryptCookies.

Example event:

<?php

namespace App\Events;

use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class DirectMessageCreated implements ShouldBroadcast
{
    /**
     * @var DirectMessage
     */
    public $directMessage;

    public function __construct(DirectMessage $directMessage)
    {
        $this->directMessage = $directMessage;
    }

    public function broadcastOn()
    {
        return new PrivateChannel(
            "http://example/user/{$this->directMessage->user_id}/direct-messages", 
        );
    }
}

Example Frontend:

var es = new EventSource('http://localhost:3000/.well-known/mercure?topic=' + encodeURIComponent('http://example/user/1/direct-messages'), { withCredentials: true });
es.addEventListener('message', (messageEvent) => {
    var eventData = JSON.parse(messageEvent.data);
    console.log(eventData);
});

Advanced usage

If you want to generate your own JWT, you can do it by overriding the mvanduijker.mercure_broadcaster.publisher_jwt service. You want to do this if you want to have custom claims, using other signing algorithms, etc. It expects a string back containing the JWT. Example how the default JWT is generated: https://github.com/mvanduijker/laravel-mercure-broadcaster/blob/master/src/LaravelMercureBroadcasterServiceProvider.php#L32

Make sure you also make the changes in the cookie middleware.

Further reading

Make sure you read the documentation of Mercure and how to run it securely (behind https).

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

mvanduijker/laravel-mercure-broadcaster 适用场景与选型建议

mvanduijker/laravel-mercure-broadcaster 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 80.75k 次下载、GitHub Stars 达 173, 最近一次更新时间为 2019 年 04 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「events」 「laravel」 「sse」 「broadcaster」 「server sent events」 「mercure」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 mvanduijker/laravel-mercure-broadcaster 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mvanduijker/laravel-mercure-broadcaster 我们能提供哪些服务?
定制开发 / 二次开发

基于 mvanduijker/laravel-mercure-broadcaster 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 80.75k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 173
  • 点击次数: 25
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 173
  • Watchers: 5
  • Forks: 20
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-04-02