easybib / api-client-php
EasyBib API的PHP客户端
Requires
- php: >=5.5
- doctrine/cache: ~1.3
- easybiblabs/oauth2-client-php: ^4.1
- guzzlehttp/guzzle: ^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^1.11
- phpmd/phpmd: ^2.4.3
- phpunit/phpunit: >=3.7
- squizlabs/php_codesniffer: ^2.6
This package is not auto-updated.
Last update: 2024-09-10 04:07:40 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
。