legionth/serin

基于 ReactPHP 的异步 Twitter API 客户端

v0.1.0 2020-05-22 12:43 UTC

This package is auto-updated.

Last update: 2024-09-14 18:20:48 UTC


README

Serin 是一个基于 ReactPHP 的异步 Twitter API 客户端

目录

快速开始

useReact\EventLoop\Factory;

require_once __DIR__ . '/../vendor/autoload.php';

$loop = Factory::create();

$oauthConsumerKey = 'SyCz6mFj7992Wy9tAcM1zQQci';
$consumerSecret = 'm349wE5VEkS3PM2FdS5eeptxoXz4o6jPHVyS1JVpGCZmYyPMqf';

$oauthToken = '3019738408-5wkZjXGk02TfyjWpMMolQHHdkQ3fr8APdkkTluk';
$tokenSecret = 'bo34Dph9tQGQC7cEk7ZBir5f9Du608FylevCAUwzw33sG';

$client = new \Legionth\Serin\Client(
    $loop,
    $oauthConsumerKey,
    $consumerSecret,
    $oauthToken,
    $tokenSecret
);

$response = $client->tweet('does this work?');

$response->then(function (\Psr\Http\Message\ResponseInterface $response) use ($client) {
    echo \RingCentral\Psr7\str($response);
}, function (Exception $exception) {
    echo(\RingCentral\Psr7\str($exception->getResponse()));
});

$loop->run();

上面的代码将在指定的账号上创建一条推文。

与其他库相比有何不同?

虽然其他用 PHP 编写的 Twitter API 客户端使用像 Curl 这样的扩展来发送 HTTP 请求,但此库使用 100% 纯 PHP。使用 ReactPHP 使得此库完全异步。

如何使用此库

Client 类是用于与 Twitter API 通信所必需的。只需输入 Twitter 机密和令牌,然后使用 Client 与 Twitter 进行交互。

之前从未使用过 Twitter API?请使用官方的 Twitter 开发者指南 来创建此库所需的令牌和机密。

此库使用 ReactPHP,因此整个库基于非阻塞概念。这就是为什么每个 Client 方法都会返回一个 Promise,当服务器回答请求时,它将导致一个 PSR-7 响应。在此期间,可以发送其他请求,而无需等待之前的请求完成(除非你想这样做)。

$response = $client->tweet('does this work?');
$responseSecondTweet = $client->tweet('of course it does');

$response->then(function (\Psr\Http\Message\ResponseInterface $response) use ($client) {
    echo \RingCentral\Psr7\str($response);
}, function (Exception $exception) {
    echo(\RingCentral\Psr7\str($exception->getResponse()));
});

$responseSecondTweet->then(function (\Psr\Http\Message\ResponseInterface $response) use ($client) {
    echo \RingCentral\Psr7\str($response);
}, function (Exception $exception) {
    echo(\RingCentral\Psr7\str($exception->getResponse()));
});

端点

查看 Client 方法以获取所有可能端点的概述。此库尽可能接近于 官方 Twitter API 的实际措辞。

自定义请求

如果缺少某些端点?不用担心,创建一个包含所有必要数据的 PSR-7 请求。

客户端将使用所需的 OAuth 1.0a 身份验证对您的请求进行身份验证。

$client = new \Legionth\Serin\Client(
    $loop,
    $oauthConsumerKey,
    $consumerSecret,
    $oauthToken,
    $tokenSecret
);

$request = new RingCentral\Psr7\ServerRequest(
    'POST',
    'https://api.twitter.com/1.1/statuses/update.json',
    [ 'Content-Type' => 'application/x-www-form-urlencoded'],
    'status=' . rawurlencode('Hello World'),
);

$response = $client->tweet($request);

想在库中添加一个端点?请发起一个 Pull Request 或联系我!

身份验证

此库中的 OAuth 1.0a 身份验证将用于发送推文、转发和获取状态信息。因此,为了使用此库,需要在 Twitter API 中进行注册。

安装

安装此库的推荐方式是通过 Composer

初次使用 Composer?

这将安装最新支持的版本

$ composer require legionth/serin:^0.1.0

许可证

查看 许可证文件