teamones/phpcent

PHP 库,用于与 Centrifugo HTTP API 通信(使用 Workerman 支持异步请求)

4.1.0 2021-06-30 03:53 UTC

This package is auto-updated.

Last update: 2024-09-29 05:43:15 UTC


README

Build Status Latest Version

PHP 库,用于与 Centrifugo v2 HTTP API 通信。

库已发布在 Composer 上:https://packagist.org.cn/packages/centrifugal/phpcent

composer require centrifugal/phpcent:~3.0

参见 Centrifugo 文档

基本用法

$client = new \phpcent\Client("https://:8000/api");
$client->setApiKey("Centrifugo API key");
$client->publish("channel", ["message" => "Hello World"]);

您可以使用 phpcent 创建连接令牌(JWT)

$token = $client->setSecret("Centrifugo secret key")->generateConnectionToken($userId);

有效期为 5 分钟的连接令牌

$token = $client->setSecret("Centrifugo secret key")->generateConnectionToken($userId, time() + 5*60);

还可以生成私有频道订阅令牌

$token = $client->setSecret("Centrifugo secret key")->generatePrivateChannelToken($client, $channel);

还可以在构造函数中设置 API 密钥和密钥

$client = new \phpcent\Client("https://:8000/api", "Centrifugo API key", "Centrifugo secret key");

超时

$client->setConnectTimeoutOption(0); // Seconds | 0 = never
$client->setTimeoutOption(2); // Seconds

所有可用的 API 方法

$response = $client->publish($channel, $data);
$response = $client->broadcast($channels, $data);
$response = $client->unsubscribe($channel, $userId);
$response = $client->disconnect($userId);
$response = $client->presence($channel);
$response = $client->presenceStats($channel);
$response = $client->history($channel);
$response = $client->historyRemove($channel);
$response = $client->channels();
$response = $client->info();

在解码响应中的 JSON 时使用 assoc 选项

$client->setUseAssoc(true);

SSL

如果您的 Centrifugo 服务器有无效的 SSL 证书,您可以

$client->setSafety(false);

您还可以安全地使用自签名证书

$client = new \phpcent\Client("https://:8000/api");
$client->setCert("/path/to/certificate.pem");
$client->setCAPath("/ca/path"); // if you need.

注意:证书必须与 Client 地址中的主机名匹配(例如上面的 localhost)。

DNS 解析

此错误可能表示您的系统在解析 IPv6 地址时存在问题

cURL error: Resolving timed out after [value] milliseconds

默认情况下,将尝试解析 IPv4 和 IPv6 地址。您可以使用以下方法强制只解析 IPv4 地址:

$client->forceIpResolveV4();

测试

要求

提供的 PHPUnit 测试假设有一个本地的 Centrifugo 服务器正在运行,并且可以通过端口 8000 访问。这可以通过使用 Docker 和 官方 Centrifugo 镜像 实现。

# Install package dependencies.
$ composer install

# The following command starts a Centrifugo server running in a background Docker container.
$ docker run -d -p 8000:8000 --name centrifugo centrifugo/centrifugo centrifugo --api_insecure

# Run the test suite.
$ vendor/bin/phpunit

# Shut down the Centrifugo container.
$ docker stop centrifugo

作者