定制 zfr/zfr-pusher 二次开发

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

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

zfr/zfr-pusher

Composer 安装命令:

composer require zfr/zfr-pusher

包简介

PHP library for interacting with the Pusher REST API

README 文档

README

Build Status Latest Stable Version

Introduction

This is an unofficial Pusher PHP client for interacting with the REST Pusher API. Contrary to the official client, ZfrPusher is based on modern tools and with a better architecture.

Dependencies

Integration with frameworks

To make this library even more easier to use, here are various libraries:

Want to do an integration for another framework? Open an issue, and I'll open a repository for you!

Installation

We recommend you to use Composer to install ZfrPusher. Just add the following line into your composer.json file:

{
    "require": {
        "zfr/zfr-pusher": "1.*"
    }
}

Then, update your dependencies by typing: php composer.phar update.

Tutorial

ZfrPusher is separated into two ways: the client object (ZfrPusher\Client\PusherClient class) which allows to execute Guzzle commands manually, and the service object (ZfrPusher\Service\PusherService class) which is a thin layer around the client that aims to simplify usage and error handling.

This is how you create a Pusher service:

use ZfrPusher\Client\Credentials;
use ZfrPusher\Client\PusherClient;
use ZfrPusher\Service\PusherService;

$credentials = new Credentials('application-id', 'key', 'secret');
$client      = new PusherClient($credentials);
$service     = new PusherService($client);

Once you have access to the service, you can perform any operations.

Triggering events

To trigger an event to one or more channels, use the trigger method. First parameter can either be a single channel (string), or multiple channels (an array of strings):

// Single channel
$service->trigger('my-channel-1', 'my-event', array('key' => 'value'));

// Multiplie channels
$service->trigger(array('my-channel-1', 'my-channel-2'), 'my-event', array('key' => 'value'));

trigger method also supports a fourth parameter, which is the socket id to exclude a specific socket from receiving the message (more information here):

// Exclude socket '1234.1234'
$service->trigger('my-channel-1', 'my-event', array('key' => 'value'), '1234.1234');

Finally, trigger method also supports a fifth parameter which is used to make an asynchronous trigger. This means that it immediately returns to the client, without waiting for the response. By default, all trigger requests are done synchronously:

// Force the trigger to be asynchronous
$service->trigger('my-channel-1', 'my-event', array('key' => 'value'), '', true);

Pusher service also provides a shortcut for doing asynchronous requests with the triggerAsync method, as shown above:

$service->triggerAsync('my-channel-1', 'my-event', array('key' => 'value'));

Channel(s) information

You can fetch information about a single channel using the getChannelInfo method, with an optional array of information you want to retrieve (currently, Pusher API only supports user_count and subscription_count values:

$result = $service->getChannelInfo('my-channel', array('user_count'));

You can use the method getChannelsInfo to get information about multiple channels, optionally filtered by name. Like getChannelInfo, this method accepts an optional second parameter which is an array of information to retrieve.

// Get information about all channels whose name begins by 'presence-'
$result = $service->getChannelsInfo('presence-');

Presence channel users

You can retrieve all the users in a presence channel user using the getPresenceUsers method:

$result = $service->getPresenceUsers('presence-foobar');

Authenticate private channels

To authenticate a user against a private channel, call the authenticatePrivate method, with channel name and socket id. This method returns an array whose key is 'auth' and whose value is the signed authentication string. It's up to you to encode this as a JSON string (typically done in a controller in a MVC architecture) to return it to the client:

$result = $service->authenticatePrivate('private-channel', '1234.1234');

var_dump($result); // prints array('auth' => 'authentication-string')

Authenticate presence channels

To authenticate a user against a presence channel, call the authenticatePresence method, with channel name, socket id and user data. This method returns an array that contains values for auth and channel_data keys. It's up to you to encode this as a JSON string (typically done in a controller in a MVC architecture) to return it to the client:

$result = $service->authenticatePresence('presence-channel', '1234.1234', array('firstName' => 'Michael'));

var_dump($result); // prints array('auth' => 'authentication-string', 'channel_data' => '{"firstName":"Michael"}')

General authentication

For ease of use, service also has a generic authenticate method that choose the right method according to channel name:

$result = $service->authenticate('private-channel', '1234.1234');
$result = $service->authenticate('presence-channel', '1234.1234', array('firstName' => 'Michael'));

Advanced use

Error handling

When using the Pusher service, all exceptions that may occurred are handled, so that you can easily filter Pusher errors. All Pusher exceptions implement the ZfrPusher\Exception\ExceptionInterface:

use ZfrPusher\Exception\ExceptionInterface as PusherExceptionInterface;

try {
    $result = $service->getPresenceUsers('presence-foobar');
} catch (PusherExceptionInterface $e) {
    // Handle exception
}

Service instantiate concrete exceptions based on the error status code:

  • ZfrPusher\Service\Exception\UnauthorizedException: thrown when Pusher REST API returns a 401 error (not authorized).
  • ZfrPusher\Service\Exception\ForbiddenException: thrown when Pusher REST API returns a 403 error (when the application may be disabled, or when you have reached your messages quota).
  • ZfrPusher\Service\UnknownResourceException: thrown when Pusher REST API returns a 404 error (may occur when you ask information about an unknown channel, for instance)
  • ZfrPusher\Service\RuntimeException: thrown for any other errors.

In all cases, you can find more information about the error by calling php $exception->getMessage();.

Usage example:

use ZfrPusher\Exception\ExceptionInterface as PusherExceptionInterface;
use ZfrPusher\Service\Exception\ForbiddenException;

try {
    $result = $service->getPresenceUsers('presence-foobar');
} catch(ForbiddenException $e) {
    // Oops, we may have reached our messages quota... Let's do something!
} catch (PusherExceptionInterface $e) {
    // Any other Pusher exception...
} catch (\Exception $e) {
    // Any other non-Pusher exception...
}

Debug applications

In the official Pusher PHP client, you can attach a logger directly to the client through a set_logger method. While simple, this was a bad way of doing it as it was hard-coded into the client (and your logger had to have a log method, so your own logger may not have it). Furthermore, the places where logging occurred were hardcoded also.

Instead, ZfrPusher client takes advantage of an event manager to do this. For instance, let's say we want to log every URL BEFORE the request is sent. Let's first create a subscriber. A subscriber implements the interface Symfony\Component\EventDispatcher\EventSubscriberInterface. In the getSubscribedEvents method, we attach a listener for the event request.before_send (you can find a complete list of available hooks here):

<?php

namespace Application\Logger;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class PusherLogger implements EventSubscriberInterface
{
    /**
     * {@inheritDoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            'request.before_send' => array('log', -255)
        );
    }

    /**
     * Log something
     *
     * @param  Event $event
     * @return void
     */
    public function log(Event $event)
    {
        $request = $event['request'];
        $url     = $request->getUrl();

        // Log the URL...
    }
}

Next, we need to attach the subscriber to the client:

use ZfrPusher\Client\Credentials;
use ZfrPusher\Client\PusherClient;
use ZfrPusher\Service\PusherService;

$credentials = new Credentials('application-id', 'key', 'secret');
$client      = new PusherClient($credentials);

$client->addSubscriber(new PusherLogger());

$service = new PusherService($client);

And voilà, now all the URL will be logged.

Directly use the client

While the Pusher service is convenient, you may want to directly use the Pusher client instead, so that you can have better control of how requests are sent. You can do this:

use ZfrPusher\Client\Credentials;
use ZfrPusher\Client\PusherClient;

$credentials = new Credentials('application-id', 'key', 'secret');
$client      = new PusherClient($credentials);

// Let's do a trigger
$parameters = array(
    'event'     => 'my-event',
    'channel'   => 'my-channel',
    'data'      => array('key' => 'value'),
    'socket_id' => '1234.1234'
);

$command = $client->getCommand('Trigger', $parameters)
                  ->execute();

When using the client directly, the exceptions thrown when errors occurred are Guzzle exceptions, not Pusher exceptions. Therefore it is harder to filter Pusher only exceptions. If you want this feature, please use the service instead, or write your own wrapper around the Pusher client.

zfr/zfr-pusher 适用场景与选型建议

zfr/zfr-pusher 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 12.71k 次下载、GitHub Stars 达 21, 最近一次更新时间为 2013 年 05 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 zfr/zfr-pusher 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 12.71k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 21
  • 点击次数: 20
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 21
  • Watchers: 3
  • Forks: 7
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2013-05-21