robertmain / communique
灵活的可插拔REST客户端
v0.0.3
2016-01-10 21:23 UTC
Requires
- kdyby/curl-ca-bundle: ~1.0
- phpunit/php-token-stream: 1.4.8
Requires (Dev)
- phpdocumentor/phpdocumentor: ^2.8
- phpunit/phpunit: ^4.8
This package is auto-updated.
Last update: 2024-09-12 15:51:15 UTC
README
这是什么?
这是一个使用中间件的灵活可插拔REST客户端。该项目的目的是提供一个足够灵活的REST客户端,以便通过请求和响应拦截器(概念上类似于AngularJS,尽管实现方式略有不同)来修改请求和响应。
使用方法
典型使用
您可以使用以下代码使用REST库发出请求。请注意,get、put、post、delete等方法不返回原始响应负载,而是一个封装对象,类型为\Communique\RESTClientResponse。此对象包含
- HTTP状态码(200、201、404、500等)
- 响应负载(来自服务器的响应体)
- 服务器头部(服务器随负载返回的任何头部,这些通常对缓存控制很有用)
您可以在\Communique\RESTClientResponse文档中找到更多信息
<?php $rest = new \Communique\Communique('http://api.company.com/'); $response = $rest->get('users/1'); //Contains information about user number 1 // Since $response is actually a RESTClientResponse object (rather than the raw response payload), we can get // properties of the request like so: echo $response->status; //This will be the HTTP status code // If we want the raw request payload we do this: echo $response->payload; // Headers can be retrieved like so: echo $response->getHeader('header_key'); ?>
请求拦截器
虽然上面的例子对于发出简单请求和从API返回结果很有用,但您可能希望对请求有更多的控制。Communique提供了一个使用拦截器来完成此操作的方法。拦截器是一个具有请求和响应方法的类。每个拦截器的请求方法在每个请求上都会被调用,每个响应拦截器方法在每个响应上都会被调用。这允许在请求发送之前和返回之后对请求进行复杂修改。这允许进行诸如JSON解析、OAuth请求签名或缓存等操作。拦截器的执行顺序与提供顺序相同。如果您想添加拦截器,您可以通过将一个包含您拦截器实例的数组的第二个构造函数参数传递给Communique来实现。拦截器应实现\Communique\Interceptor接口
<?php $rest = new \Communique\Communique('http://api.company.com/', array(new JSONParser(), new OAuth())); // Use the library as before ?>
自定义HTTP客户端
此库默认附带cURL实现,但如果您希望提供自己的实现,可以使用以下方式使用第三个构造函数参数
<?php $rest = new \Communique\Communique('http://api.company.com/', array(new JSONParser(), new OAuth()), new CustomHTTPClient()); // Use the library as before ?>
许可
根据GPL许可 - 请参阅名为LICENSE的文件以获取更多信息。
联系方式
- 如果您想提交错误报告或问题,请使用GitHub上的问题跟踪器
文档
文档可以在此处找到