定制 moonshine/twirl 二次开发

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

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

moonshine/twirl

Composer 安装命令:

composer require moonshine/twirl

包简介

Web sockets for MoonShine for component reload

README 文档

README

Twirl is a lightweight, free component for integrating WebSocket updates into the MoonShine admin panel. It allows you to quickly implement real-time dynamic updates of interface elements using Centrifugo or other WebSocket servers.

Twirl features:

  • Simple HTML component updates on events
  • Easy integration with MoonShine and Centrifugo
  • Minimal dependencies, maximum speed to launch

Twirl is ideal for basic scenarios of dynamic interface updates. For advanced features—notifications, collaborative form editing, fragment updates, and integration with various WebSocket providers—use the full Rush package.

Requirements

  • MoonShine 3.0+

Install

composer require moonshine/twirl

Publish the resources and configuration:

php artisan vendor:publish --provider="Moonshine\Twirl\Providers\TwirlServiceProvider"

Quick start

Add Twirl component in your MoonShineLayout or page:

use MoonShine\Twirl\Components\Twirl;

Twirl::make(),

Now you can trigger the event and update your component:

use MoonShine\Twirl\Events\TwirlEvent;

TwirlEvent::dispatch(
    selector: '.your-selector' . $id,
    (string) Badge::make(),
    HtmlReloadAction::OUTER_HTML
);

Twirl is a thin wrapper around updating HTML elements and a convenient interface to plug into any WebSocket transport. It does not run or configure WebSocket connections for you.

You need make the bridge between Twirl and your WebSocket stack by yourself:

  • Backend: implement and bind your own broadcaster via TwirlBroadcastContract for any provider (Centrifugo, Pusher, Socket.IO, custom, etc.).
  • Frontend: subscribe to your channels with your client and pass incoming payloads to onTwirl so Twirl can apply HTML updates.

Quick checklist:

  • Implement TwirlBroadcastContract for your transport.
  • Bind it in the container.
  • On the frontend, set up subscriptions and forward publications to onTwirl() callback.

Example for Centrifugo

Caution

All examples are insecure and serve only for development

Install library for work with Centrifugo:

composer require centrifugal/phpcent:~6.0

Up the Centrifugo instance and make some configs in your app (host, api-key, jwt-secret...).

Then implement TwirlBroadcastContract with connection to Centrifugo:

<?php

/**
 * @see https://github.com/centrifugal/phpcent
 */

declare(strict_types=1);

namespace App\Services;

use Throwable;
use phpcent\Client;
use MoonShine\Twirl\DTO\TwirlData;
use MoonShine\Twirl\Contracts\TwirlBroadcastContract;

final class Centrifugo implements TwirlBroadcastContract
{
    public function send(string $channel, TwirlData $twirlData): void
    {
        try {
            $client = new Client(config('app.centrifugo.host'). '/api', config('app.centrifugo.api-key'));
            $client->publish($channel, $twirlData->toArray());
        } catch (Throwable $e) {
            report($e);
        }
    }
}

Add into provider:

$this->app->bind(TwirlBroadcastContract::class, Centrifugo::class);

Write frontend logic for connect Centrifugo with Twirl. First, install the package:

npm install centrifuge

Example:

import { Centrifuge, PublicationContext } from "centrifuge";
import axios from "axios";

declare global {
    interface Window {
        MoonShine: {
            onCallback: (name: string, callback: Function) => void;
        }
    }

    interface ImportMeta {
        env: {
            [key: string]: string;
        }
    }
}

document.addEventListener("moonshine:init", async () => {
    if (! window.MoonShine) {
        console.error('MoonShine is not initialized');
        return;
    }

    let token = await getToken();

    const centrifuge = new Centrifuge("ws://localhost:8000/connection/websocket", {
        token: token
    });

    centrifuge.on('connected', () => {
        document.dispatchEvent(new CustomEvent('moonshine:twirl'));
    }).connect();

    window.MoonShine.onCallback('onTwirl', function(channel: string, onTwirl: (data: any) => void): void {
        if(centrifuge.getSubscription(channel) !== null) {
            return;
        }

        const sub = centrifuge.newSubscription(channel);

        sub.on('publication', function(ctx: PublicationContext): void {
            onTwirl(ctx.data);
        }).on('error', (error): void => {
            console.log(error)
        })
            .subscribe()
    });
});

async function getToken(): Promise<string> {
    // Your endpoint to get a token
    const response = await axios.post('/centrifugo/token')

    return response.data.token;
}

CentrifugoController example:

use MoonShine\Laravel\Http\Controllers\MoonShineController;
use phpcent\Client;

class CentrifugoController extends MoonShineController
{
    public function index()
    {
        $client = new Client(
            url: 'http://centrifugo-url:8000/api',
            apikey: '...',
            secret: '...'
        );

        return response()->json([
            'token' => $client->generateConnectionToken($this->auth()->user()->id, channels: [
                'twirl-channel'
            ]),
        ]);
    }
}

Centrifugo config example:

{
    "client": {
        "token": {
            "hmac_secret_key": "bbe7d157-a253-4094-9759-06a8236543f9"
        },
        "allowed_origins": ["*"]
    },
    "http_api": {
        "key": "d7627bb6-2292-4911-82e1-615c0ed3eebb"
    },
    "channel": {
        "without_namespace": {
            "allow_subscribe_for_client": true,
            "allow_publish_for_client": true
        },
        "namespaces": [
            {
                "name": "twirl-channel"
            }
        ]
    },
    "admin": {
        "enabled": true,
        "password": "12345",
        "secret": "12345"
    }
}

moonshine/twirl 适用场景与选型建议

moonshine/twirl 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 428 次下载、GitHub Stars 达 2, 最近一次更新时间为 2025 年 06 月 29 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 moonshine/twirl 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 428
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 21
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 0
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-06-29