centrifugal / phpcent
用于与 Centrifugo HTTP API 通信的 PHP 库
6.0.1
2024-06-27 19:04 UTC
Requires
- php: >=7.0.0
- ext-curl: *
- ext-json: *
Requires (Dev)
- phpunit/phpunit: 9.*
This package is auto-updated.
Last update: 2024-08-27 19:31:52 UTC
README
PHP 库,用于与 Centrifugo v5 HTTP API 通信(Centrifugo v4 使用 phpcent v5.x,Centrifugo v3 使用 phpcent v4.x)。
库已发布在 Composer 上:https://packagist.org.cn/packages/centrifugal/phpcent
composer require centrifugal/phpcent:~6.0
基本用法
$client = new \phpcent\Client("http://localhost: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")->generateSubscriptionToken($userId, $channel);
还可以生成带有过期时间的频道订阅令牌,例如 30 分钟的有效期
$token = $client->setSecret("Centrifugo secret key")->generateSubscriptionToken($userId, $channel, time() + 30*60);
还可以在构造函数中设置 API 密钥和密钥
$client = new \phpcent\Client("http://localhost:8000/api", "<API key>", "<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://localhost:8000/api"); $client->setCert("/path/to/certificate.pem"); $client->setCAPath("/ca/path"); // if you need.
注意:证书必须与 Client
地址中的主机名匹配(例如上面示例中的 localhost
)。
域名解析
此错误可能表明您的系统在解析 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