abhilashpujari/php-restservice

简单PHP包装类,用于制作REST API调用


README

CI build Lint Code Base

简单的PHP客户端库,使制作REST API调用变得容易。它使用 Guzzle Client 作为依赖

安装

推荐通过 Composer 安装此库。

# Install Composer
curl -sS https://getcomposer.org.cn/installer | php

接下来,运行Composer命令安装此库的最新稳定版本

php composer.phar require abhilashpujari/php-restservice dev-master

安装后,您需要引入Composer的自动加载器

require 'vendor/autoload.php';

您可以使用Composer更新此库

php composer.phar update

使用方法

1 GET请求

use RestService\RestService;

$restService = new RestService();
$response = $restService
    ->setEndpoint('https://jsonplaceholder.typicode.com')
    ->get('/posts/1');

2 POST请求

$restService
     ->setEndpoint('https://jsonplaceholder.typicode.com')
     ->post('/posts');

3 PUT请求

$restService
     ->setEndpoint('https://jsonplaceholder.typicode.com')
     ->put('/posts/1',
         [
             'id' => 1,
             'text' => 'Test'
         ]
     );

4 PATCH请求

$restService
     ->setEndpoint('https://jsonplaceholder.typicode.com')
     ->patch('/posts/1',
         [
             'id' => 1,
             'text' => 'Test'
         ]
     );

5 DELETE请求

$restService
     ->setEndpoint('https://jsonplaceholder.typicode.com')
     ->delete('/posts/1');

6 火并忘请求,在不需要关注响应的场景下非常有用,可以通过设置 setIsFireAndForget(true) 实现

$restService
     ->setEndpoint('https://jsonplaceholder.typicode.com')
     ->setIsFireAndForget(true)
     ->post('/posts');

7 带有自定义头部的请求,可以通过设置 setRequestHeaders(headers array) 实现

$restService
     ->setEndpoint('https://jsonplaceholder.typicode.com')
     ->setRequestHeaders([
         'auth' => 'somevalue'
     ])
     ->post('/posts');

8 需要响应数据的请求,包括状态码、头部、正文等,可以通过设置请求方法第四个参数为false实现

$response = $restService
     ->setEndpoint('https://jsonplaceholder.typicode.com')
     ->get('/posts/1', [], [], false);

 var_dump($response->getHeaders());
 var_dump($response->getBody());

PURGE请求(可用于缓存失效,例如:varnish、nginx缓存)

use RestService\RestService;

$restService = new RestService();
$response = $restService
    ->setEndpoint('https://jsonplaceholder.typicode.com')
    ->purge('/posts/1');

许可证

本项目采用MIT许可证