定制 kristinasa/realtimex-php 二次开发

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

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

kristinasa/realtimex-php

最新稳定版本:v1.3.1

Composer 安装命令:

composer require kristinasa/realtimex-php

包简介

PHP client library for RealtimeX real-time messaging service

README 文档

README

PHP Version Tests License

PHP client library for RealtimeX real-time messaging service.

Installation

Composer

composer require kristinasa/realtimex-php

Quick Start

<?php

require 'vendor/autoload.php';

use RealtimeX\RealtimeX;

// Initialize
$realtimex = new RealtimeX('YOUR_API_KEY', [
    'cluster' => 'eu',  // optional, default 'eu'
    'wsHost' => 'ws.realtimex.net',  // optional
    'wsPort' => 443,  // optional
    'encrypted' => true,  // optional, default true
]);

// Subscribe to a channel
$channel = $realtimex->subscribe('my-channel');

// Listen for events
$channel->bind('my-event', function($data) {
    echo 'Received: ' . json_encode($data) . PHP_EOL;
});

// Send client events
$channel->trigger('client-my-event', [
    'message' => 'Hello'
]);

// Start event loop (blocking)
$realtimex->run();

API Reference

RealtimeX

Constructor

$realtimex = new RealtimeX($apiKey, $options);

Parameters:

  • $apiKey (string): Your RealtimeX API key
  • $options (array, optional): Configuration options
    • cluster (string): Server cluster, default 'eu'
    • wsHost (string): WebSocket host
    • wsPort (int): WebSocket port
    • encrypted (bool): Use WSS, default true
    • authEndpoint (string): Required for private and presence channels. Must return auth signature

Methods

subscribe($channelName)

$channel = $realtimex->subscribe('my-channel');
$privateChannel = $realtimex->subscribe('private-my-channel');
$presenceChannel = $realtimex->subscribe('presence-my-channel');

unsubscribe($channelName)

$realtimex->unsubscribe('my-channel');

disconnect()

$realtimex->disconnect();

run()

// Start blocking event loop
$realtimex->run();

process()

// Process one message (non-blocking)
$realtimex->process();

Channel

Methods

bind($event, $callback)

$channel->bind('my-event', function($data) {
    echo 'Event data: ' . json_encode($data) . PHP_EOL;
});

bind_global($callback)

$channel->bind_global(function($event, $data) {
    echo "Event $event: " . json_encode($data) . PHP_EOL;
});

trigger($event, $data)

// Client events must start with 'client-'
$channel->trigger('client-my-event', [
    'message' => 'Hello World'
]);

unbind($event, $callback = null)

// Remove specific callback
$channel->unbind('my-event', $myCallback);

// Remove all callbacks for event
$channel->unbind('my-event');

unsubscribe()

$channel->unsubscribe();

Connection Events

$realtimex->connection->bind('connected', function() {
    echo 'Connected to RealtimeX' . PHP_EOL;
});

$realtimex->connection->bind('disconnected', function() {
    echo 'Disconnected from RealtimeX' . PHP_EOL;
});

$realtimex->connection->bind('error', function($err) {
    echo 'Connection error: ' . $err['message'] . PHP_EOL;
});

Channel Types

Public Channels

$channel = $realtimex->subscribe('my-channel');

Private Channels

$privateChannel = $realtimex->subscribe('private-my-channel');

Presence Channels

$presenceChannel = $realtimex->subscribe('presence-my-channel');

Authentication

Private and presence channels require authentication. You must provide an authEndpoint that returns authorization data.

Note: There is no default authEndpoint. If you attempt to subscribe to a private or presence channel without providing authEndpoint, an error will be thrown.

Setup Auth Endpoint

$realtimex = new RealtimeX('YOUR_API_KEY', [
    'authEndpoint' => 'https://your-backend.com/auth'  // Required for private/presence channels
]);

Auth Endpoint Implementation

Your backend must implement a POST endpoint that:

  • Receives {socket_id, channel_name} in request body
  • Returns {auth: "key:signature"} response

Request Format:

{
  "socket_id": "SZ7iV2C0J9Fd9vjgAABB",
  "channel_name": "private-test-channel"
}

Response Format:

{
  "auth": "your_app_key:generated_signature"
}

Presence Channels

Presence channels require both auth and channel_data (stringified JSON with user information).

Example:

$presence = $realtimex->subscribe('presence-chat');

Expected server auth response for presence channels:

{
  "auth": "your_app_key:generated_signature",
  "channel_data": "{\"user_id\":\"123\", \"user_info\": {\"name\":\"Alice\"}}"
}

Example (PHP):

<?php

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);
$socketId = $input['socket_id'];
$channelName = $input['channel_name'];

$auth = hash_hmac('sha256', "$socketId:$channelName", YOUR_APP_SECRET);

$response = [
    'auth' => YOUR_APP_KEY . ':' . $auth
];

// For presence channels, add channel_data
if (strpos($channelName, 'presence-') === 0) {
    $response['channel_data'] = json_encode([
        'user_id' => '123',
        'user_info' => ['name' => 'Alice']
    ]);
}

echo json_encode($response);

SDK Request: SDK sends a POST request to authEndpoint with JSON body. You may customize authentication on your backend.

WebSocket Protocol

Connection

ws://your-host:port?api_key=YOUR_API_KEY

Message Format

Subscribe:

{
  "event": "realtimex:subscribe",
  "data": {
    "channel": "my-channel",
    "auth": "<optional-auth>",
    "channel_data": "<optional-json>"
  }
}

Unsubscribe:

{
  "event": "realtimex:unsubscribe",
  "data": {
    "channel": "my-channel"
  }
}

Successful Subscription:

{
  "event": "realtimex_internal:subscription_succeeded",
  "data": {
    "channel": "my-channel",
    "initial_state": {}
  }
}

Client Event:

{
  "event": "client-my-event",
  "channel": "my-channel",
  "data": { "message": "Hello" }
}

Server Event:

{
  "event": "server-event",
  "data": {
    "event": "my-event",
    "channel": "my-channel",
    "data": { "message": "Hello" }
  }
}

Compatibility

PHP Support

  • PHP 8.1+
  • PHP 8.2+
  • PHP 8.3+

Dependencies

  • textalk/websocket: WebSocket client library
  • guzzlehttp/guzzle: HTTP client for authentication

Reconnection

RealtimeX SDK automatically handles connection failures and reconnects:

  • Fixed delay: 3 seconds between reconnection attempts (no exponential backoff)
  • Automatic resubscription: All existing channels are automatically resubscribed after reconnect
  • Event firing: connected event fires after each successful reconnection
  • Channel preservation: Channel instances remain valid across reconnections
  • Pending subscriptions: Subscriptions made while disconnected are queued and sent on reconnect

Example:

$realtimex->connection->bind('connected', function() {
    echo 'Connected (or reconnected)' . PHP_EOL;
});

$realtimex->connection->bind('disconnected', function() {
    echo 'Disconnected - will auto-reconnect in 3s' . PHP_EOL;
});

Features

✅ WebSocket connection management
✅ Channel subscription/unsubscription
✅ Event listening and triggering
✅ Client events
✅ Automatic reconnection
✅ Private and presence channels
✅ Authentication support
✅ PSR-4 autoloading
✅ Full unit test coverage
✅ PHP 8.1+ with modern features
✅ SOLID principles

Development

Prerequisites

Install PHP 8.1+:

# macOS
brew install php

# Verify
php -v

Install Composer:

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

Setup

# Install dependencies
composer install

# Run tests
./vendor/bin/phpunit

# Run specific test
./vendor/bin/phpunit tests/EventDispatcherTest.php

# Run with coverage
./vendor/bin/phpunit --coverage-html coverage/

Example Usage

Basic Example

<?php

require 'vendor/autoload.php';

use RealtimeX\RealtimeX;

$realtimex = new RealtimeX('YOUR_API_KEY');

$channel = $realtimex->subscribe('chat-room');

$channel->bind('new-message', function($data) {
    echo "New message: {$data['text']}" . PHP_EOL;
});

$channel->trigger('client-new-message', [
    'text' => 'Hello from PHP!',
    'user' => 'Alice'
]);

// Start event loop
$realtimex->run();

Private Channel Example

<?php

require 'vendor/autoload.php';

use RealtimeX\RealtimeX;

$realtimex = new RealtimeX('YOUR_API_KEY', [
    'authEndpoint' => 'https://your-backend.com/auth'
]);

$privateChannel = $realtimex->subscribe('private-notifications');

$privateChannel->bind('notification', function($data) {
    echo "Private notification: {$data['message']}" . PHP_EOL;
});

$realtimex->run();

Presence Channel Example

<?php

require 'vendor/autoload.php';

use RealtimeX\RealtimeX;

$realtimex = new RealtimeX('YOUR_API_KEY', [
    'authEndpoint' => 'https://your-backend.com/auth'
]);

$presenceChannel = $realtimex->subscribe('presence-online-users');

$presenceChannel->bind('user-joined', function($data) {
    echo "User joined: {$data['name']}" . PHP_EOL;
});

$presenceChannel->bind('user-left', function($data) {
    echo "User left: {$data['name']}" . PHP_EOL;
});

License

MIT

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-12-09