pubnub/pubnub

这是官方的 PubNub PHP SDK 仓库。


README

Build Status codecov Docs GitHub release (latest by date)

这是官方的 PubNub PHP SDK 仓库。

PubNub 负责您应用程序实时通信层所需的基础设施和 API。专注于您应用程序的逻辑,让 PubNub 在 100 毫秒内处理全球范围内的数据发送和接收。

该 SDK 支持 PHP 7.4 和 8.x。

获取密钥

您需要发布和订阅密钥来验证您的应用程序。从管理员门户获取您的密钥。

配置 PubNub

  1. 将 PHP SDK 集成到您的项目中

    • 不使用 composer

      1. 克隆以下仓库: git clone https://github.com/pubnub/php.git ./pubnub-php

      2. src 文件夹复制到您的项目中。

      3. 在您的项目中包含 autoloader.php 文件

        require_once('src/autoloader.php');
      4. https://github.com/Seldaek/monolog 下载依赖项 monolog,并将 monolog 文件夹从 src 文件夹复制到您的项目的 src 文件夹中。

      5. https://github.com/php-fig/log/tree/master 下载依赖项 psr/Log,并将 psr 文件夹复制到您的项目的 src 文件夹中。

      6. https://github.com/WordPress/Requests 下载依赖项 rmccue,并将 Requests 文件夹和 Requests.php 文件从 library 文件夹复制到您的项目的 src 文件夹中。

    • 使用 composer

      1. 将 PubNub 包添加到您的 composer.json 文件中

        {
            "require": {
                <!-- include the latest version from the badge at the top -->
                "pubnub/pubnub": "7.0.1"
            }
        }
      2. 从命令行运行 composer install --no-dev‌。这将 PubNub PHP SDK 及其所有依赖项安装到项目的 vendor 文件夹中。

      3. 在您的项目中包含 autoload.php 文件

        require_once('vendor/autoload.php');‌
  2. 配置您的密钥

    $pnconf = new PNConfiguration();
    $pubnub = new PubNub($pnconf);
    
    $pnconf->setSubscribeKey("mySubscribeKey");
    $pnconf->setPublishKey("myPublishKey");
    $pnconf->setUserId("ReplaceWithYourClientIdentifier");

添加事件监听器

class MySubscribeCallback extends SubscribeCallback {
    function status($pubnub, $status) {
        if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
        // This event happens when radio / connectivity is lost
        } else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory){
        // Connect event. You can do stuff like publish, and know you'll get it // Or just use the connected event to confirm you are subscribed for // UI / internal notifications, etc
        } else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory){
        // Handle message decryption error. Probably client configured to // encrypt messages and on live data feed it received plain text.
        }
    }
    function message($pubnub, $message){
    // Handle new message stored in message.message
    }
    function presence($pubnub, $presence){
    // handle incoming presence data
    }
}

$subscribeCallback = new MySubscribeCallback();
$pubnub->addListener($subscribeCallback);

发布/订阅

$pubnub->subscribe()
    ->channels("hello_world")
    ->execute();

$pubnub->publish()
    ->channel("hello_world")
    ->message("Hello PubNub!")
    ->sync();

文档

支持

如果您 需要帮助 或有 一般问题,请联系 support@pubnub.com