arthof/fake-api-client

JSONPlaceholder API 的 PHP 客户端

v1.0.0 2018-10-27 13:41 UTC

This package is not auto-updated.

Last update: 2024-09-23 16:48:19 UTC


README

PHP 客户端用于 JSONPlaceholder API
此客户端仅支持 帖子 模型请求。

需求

  • PHP 7.0
  • cURL 库

安装

通过 Composer

composer require arthof/fake-api-client

如何使用

require_once(__DIR__ . '/vendor/autoload.php');

use FakeApiClient\Client;
$Client = new Client();
$postId = 1;
$userId = 2;

//[GET] fetch single post 
$post = $Client->Posts->Fetch($postId);

//[GET] fetch all posts
$posts = $Client->Posts->FetchAll();

//[GET] fetch posts by user
$postsByUser = $Client->Posts->FetchByUser($userId);

//[GET] fetch post comments
$postComments = $Client->Posts->FetchComments($postId);

//[POST] create post
$createPost = [
    'title' => 'Lorem ipsum',
    'body' => 'Sample text',
    'userId' => 3,
];
$newPost = $Client->Posts->Create($createPost);

//[PUT] replace post
$postId = 74;
$replacePost = [
    'id' => 74,
    'title' => 'Lorem ipsum',
    'body' => 'Sample text',
    'userId' => 3,
];
$replacedPost= $Client->Posts->Replace($postId, $replacePost);

//[PATCH] update post
$postId = 74;
$replacePost = [
    'title' => 'Winnie the Pooh',
];
$updatedPost = $Client->Posts->Update($postId, $replacePost);

//[DELETE] delete post
$deletedPost = $Client->Posts->Delete($postId);

配置

如果 API URL 发生变化(默认:https://jsonplaceholder.typicode.com/),您可以在构造函数中将新 URL 传递给客户端类。
您还可以使用不同的 HTTP 客户端,只需实现 IHttpMethods 接口即可。

use FakeApiClient\Client;
$httpClient = new DifferentHttpClient();
$Client = new Client('https://new-api-url/', $httpClient);

扩展

要添加对其他模型的支持,只需创建一个新的类,该类扩展 Resources 抽象类并设置 TYPE 常量。
关于 待办事项 模型的示例

//src/FakeApiClient/Todos.php
namespace FakeApiClient;

use FakeApiClient\Resources;

class Todos extends Resources
{
    const TYPE = 'todos';
}

在 Client.php 中添加新模型变量并在构造函数中初始化它

//src/FakeApiClient/Client.php
namespace FakeApiClient;

class Client
{
    public $Posts;
    public $Todos;

    public function __construct(string $baseUrl=null, IHttpMethods $httpClient=null)
    {
        $this->Posts = new Posts($baseUrl, $httpClient);
        $this->Todos = new Todos($baseUrl, $httpClient);
    }
}

新模型将自动支持方法

  • 显示资源 [GET]
  • 列出资源 [GET]
  • 创建资源 [POST]
  • 替换资源 [PUT]
  • 更新资源 [PATCH]
  • 删除资源 [DELETE]

示例使用

use FakeApiClient\Client;
$Client = new Client();

//[GET] fetch all todos
$todos = $Client->Todos->FetchAll();