palanik / wrapi
调用 Restful API 的包装器
v0.1.7
2018-01-22 02:10 UTC
Requires
- php: >=5.5.0
- guzzlehttp/guzzle: >=6.1.0
- sabre/uri: ^1.0
Requires (Dev)
- internations/http-mock: 0.7.0
- phpunit/phpunit: ^4.0
README
调用 Restful API 的包装器
wrapi
允许您像调用普通 PHP 函数一样调用基于 HTTP 的 API。
安装
使用 Composer 安装
- 更新您的
composer.json
以要求palanik/wrapi
包。 - 运行
composer install
将 wrapi 添加到您的 vendor 目录。
{ "require": { "palanik/wrapi": "*" } }
或者简单地运行
composer require palanik/wrapi
快速入门
方法 I
查看 示例代码
方法 II
查看 示例代码
端点数组
根据以下规范声明每个端点。
"function_name" => array( "method" => "HTTP_METHOD", // 'GET', 'POST', 'PUT', 'PATCH' or 'DELETE' "path" => "relative/path/to/:api/endpoint" // Can use `Slim`/`express` style path params )
例如,github.com API 的一小部分
array( "repo" => array( "method" => "GET", "path" => "repos/:owner/:repo" ), "contributors" => array( "method" => "GET", "path" => "repos/:owner/:repo/contributors" ), "languages" => array( "method" => "GET", "path" => "repos/:owner/:repo/languages" ), "tags" => array( "method" => "GET", "path" => "repos/:owner/:repo/tags" ), "branches" => array( "method" => "GET", "path" => "repos/:owner/:repo/branches" ) )
包装端点
从 wrapi
创建 API 客户端对象。提供 API 的基础 URL 和端点数组。 wrapi
将创建一个包含所有必需函数的客户端对象。
$endpoints = array(...); $client = new wrapi\wrapi('https://api.github.com/', // base url for the API endpoints // your endpoints array ); // client object contains functions to call the API
注册
使用函数名在客户端对象中注册额外的 API 端点。
$client("zen", array( "method" => "GET", "path" => "zen" ) );
进行调用
带参数调用函数。
// This will make GET request to 'https://api.github.com/repos/guzzle/guzzle/contributors' $contributors = $client->contributors('guzzle', 'guzzle'); $zenQuote = $client->zen(); echo "Today's quote: ". $zenQuote;
API
wrapi
是一个开放式框架,不受任何单一或一组公共 API 的限制。所有提供 HTTP 接口以访问端点的 API 都可以通过 wrapi
进行包装,以便您可以快速构建客户端应用程序。
端点定义
method
和 path
/url
是必需的。
method
- 以下任一 HTTP 方法path
- API 端点的路由路径。支持express
风格的 路径参数query
- 一个包含键值对的关联数组。这是可选的。当资源通过查询字符串参数标识时很有用url
- 完全限定的 uri 字符串,用于覆盖。当 API 调用连接到不同的端点时很有用
客户端对象
wrapi
对象方便地提供了对 API 的客户端接口。通过调用 new
wrapi\wrapi()
创建它。
构造函数接受以下参数
baseURL
- API 的基础 URL。例如,https://api.github.com/repos/guzzle/guzzle/contributors
endpoints
- 列出 API 端点的数组。提供空数组或部分列表,稍后注册端点。options
- 可选参数。wrapi
使用 Guzzle 模块连接到 API 服务器。options
参数与Guzzle
请求中使用的相同options
参数。
注册函数
将端点添加到客户端对象。
$client(function_name, endpoint_definition)
function_name
- 端点的别名,也是要调用的函数名称。endpoint_definition
- 定义端点的数组。
函数调用
通过客户端对象中的函数调用API。函数的参数取决于端点数组中API的声明。
按以下顺序提供参数
- 在端点URL路径中命名的
params
。例如:$client->contributors('guzzle', 'guzzle') // guzzle (所有者) & guzzle (仓库) 是路径参数
querystring
- 以键值对形式存在的关联数组。例如:$client->contributors(array("since" => 364) // 查询字符串 ?since=364
body
-POST
或PUT
方法的JSON内容。如果不需要,则跳过此参数。
示例
示例在文件夹中。