easybib/api-client-php

EasyBib API的PHP客户端

2.4.0 2018-06-05 12:14 UTC

README

使用此工具从EasyBib API请求数据。客户端底层使用Guzzle进行实际的HTTP调用。

安装

此库需要PHP 5.5或更高版本。

使用Composer将此项目添加到项目的依赖中。

您的Composer JSON文件

"repositories":[
    {
        "type": "vcs",
        "url": "git@github.com:easybiblabs/api-client-php.git"
    }
],
"require": {
    "php":">=5.5.0",
    "easybib/api-client-php": "~0.2"
}

设置JSON后,将安装此包

composer.phar install

用法

实例化

目前支持两种OAuth授权类型:JSON Web Token和授权码。

JSON Web Token授权

use EasyBib\Api\Client\ApiBuilder;

// $redirector is your implementation of RedirectorInterface
$apiBuilder = new ApiBuilder();

$api = $apiBuilder->createWithJsonWebTokenGrant([
    'client_id' => 'client_123',
    'client_secret' => 'secret_987',
    'subject' => 'user_id_123',
]);

$user = $api->getUser();  // user serves as the entry point for traversing resources

$titleOfFirstProject = $user->get('projects')[0]->title;
$citationsFromFirstProject = $user->get('projects')[0]->get('citations');
$linksForSecondProject = $user->get('projects')[1]->getLinkRefs();

授权码授权

为了使用授权码授权,您需要实现OAuth2客户端库中的RedirectorInterface,以便允许API客户端重定向用户并获取授权码。您可以在该项目的README中找到更多信息。

use EasyBib\Api\Client\ApiBuilder;

$apiBuilder = new ApiBuilder();

// $redirector is your implementation of RedirectorInterface
$apiBuilder->setRedirector($redirector);

$api = $apiBuilder->createWithAuthorizationCodeGrant([
    'client_id' => 'client_123',
    'redirect_url' => 'http://myapp.example.com/handle-token-response',
]);

$user = $api->getUser();  // user serves as the entry point for traversing api resources

检索API资源

一旦您有了API对象,您可以使用它来遍历API。两个入口点是$api->getUser()$api->getProjects()

getUser()将返回代表用户的ApiResource;在用户API资源上调用getResourceData()->getRelations()将返回一组可从用户调用的可用引用。因此,特定项目的引用调用链可能是

$api->get('project 123')->get('citations');

这将返回一个引用的Collection。更多示例

$titleOfFirstProject = $user->get('projects')[0]->title;
$citationsFromFirstProject = $user->get('projects')[0]->get('citations');
$linksForSecondProject = $user->get('projects')[1]->getRelations();
$linksForSecondProject = $user->get('projects')[1]->listRelations();
$linksForSecondProject = $user->get('projects')[1]->hasRelation('citations');
$newProject = $user->post('projects', [
    'data' => [
        'name' => 'Some project',
        'defaultstyle' => 'mla',
    ]
]);

会话后端

默认情况下,ApiBuilder使用由Symfony会话接口包装的原生PHP会话。您可以实现不同的会话后端;有关更多信息,请参阅Symfony文档

$apiBuilder = new ApiBuilder();
$session = new Session($myCustomBackend);
$apiBuilder->setSession($session);

重置会话

在用户注册或登录时,当访客用户需要与永久用户帐户关联的新令牌时,可以重置OAuth2客户端的令牌存储。在这种情况下,使用API的应用程序必须实例化一个新的ApiTraverser或调用setCache(),使用新的缓存或缓存命名空间,以确保ApiTraverser不会返回在原始会话期间缓存的API资源。

默认情况下,ApiTraverser使用基于PHP数组的缓存,因此除非您已实现不同的缓存后端,否则您可以直接或通过ApiBuilder实例化一个新的ApiTraverser