yiiman/apistorm

创建现代IDE可识别的、结构化的API和分类响应

v0.0.3 2022-03-29 11:10 UTC

This package is auto-updated.

Last update: 2024-08-30 01:50:07 UTC


README

创建现代IDE可识别的、结构化的API和分类响应

问题是什么?

大多数SDK中存在的一个大问题是输入/输出数组/对象

例如,你有一个virtualizor api SDK

在这个SDK中,使用每个方法之前,你应该阅读的是virtualizor网站

例如,我想使用addsrv方法

$sdk->addsrv(
[
    'serid' => 0,
    'slave_server' => 1, // Pass the slave server ID if you want to create VPS on the Slave Server
    'virt' => 'kvm',
    'uid' => 0,
    'user_email' => 'test@test.com',
    'user_pass' => 'test123',
    'fname' => '',
    'lname' => '',
    'plid' => 0,
    'osid' => 88,
    'hostname' => 'test12345.com',
    'rootpass' => 'test123',
    'ips' => ['192.168.111.49'],
    'num_ips6' => 0,
    'num_ips6_subnet' => 0,
    'stid' => 1,
    'space' => [
                0=>[
                     'size' => 2,
                     'st_uuid'=>'ngavdbegidnbme2d'
                   ],
                1=>[
                    'size'=>2,
                    'st_uuid'=>'ngavdbegidnbme2d'
                   ],
                   
                ],//For VPS with Multi-Disk
    'ram' => 1024,
    'swapram' => 0,
    'bandwidth' => 0,
    'network_speed' => 0,
    'cpu' => 1000,
    'cores' => 4,
    'cpu_percent' => 100.00,
    'vnc' => 1,
    'vncpass' => 'test123',
    'kvm_cache' => 0,
    'io_mode' => 0,
    'vnc_keymap' => 'en-us',
    'nic_type' => 'default',
    'osreinstall_limit' => 0,
]
);

对于一个API方法来说,这是很糟糕的

每次你需要使用这个API时,都必须先从他们的网站上阅读API文档,因为你不知道数组参数

然后你将从这个方法请求后得到一个数组!!!

这是错误且低效的

什么是apiStorm

apiStorm可以为每个API方法的输入/输出参数进行分类

通过apiStorm,每个现代IDE都可以解析你的输入参数和输出方法数据

你可以使用apiStorm在发送到API之前验证数据

apiStorm有什么不同?

这是一个简单的传统API数据发送

$api = new TestApi();//This is a test API SDK class
$response=$api->createProduct(//This method will send data to server
    [//Our data is an array!
        'name'=>'Pen',//We dont know this parameter is require on optional!
        'category'=>10,//We can't validate data with simple not classified array input
        'color'=>'#fffff',//We dont know accepted data types for every array index
        'status'=>1,
        'price'=>3000
    ]
);
//$response is an array! and we dont know what is happening in every method without read documents

这是使用apiStorm的现代API

$api = new TestApi();//This is a test API SDK class
$data = new PostCreateProduct();//This is our input Class that extended from apiStorm classes

$data->name0 = 'Pen';//This is an required input field because its ends with "0"
$data->category0 = 10; 
$data->color0 = "#fffff";//if fields that ends with "0" be empty, then will be error on validate
$data->status0 = 1;//Now name of this field is "status0" that's mean this field is required but when data sending to server it will convert to "status"
$data->price=3000;//This is an optional input field

if ($data->validate()) {//You can validate data types before send
    $response = $api->createProduct($data);//This method will send data to server
    if ($response && $response->isSuccess()) {//Here we check status of sent request
        echo $response->created_id;//If success we have classified response 
    }else{
        var_export($response->getError());//If error, we have classified error
    }
}

在第二个示例中,PHPStorm可以像这样解析输入/输出字段

PHPSTORM中的输入字段

PHPSTORM中的分类响应

安装apiStorm

composer require yiiman/apistorm

或者

"require": {
    "yiiman/apistorm": "^0.0.1"
  }

概念

标准SDK的推荐结构如下

---src\
    |
    ---Responses\
        |
        ---ResponseClass1.php                      // extended from YiiMan\ApiStorm\Response\BaseResponse
        |--- public $responseField1='int';         // you can define one of this data types : int|string|float|serialize|json|array|class|classArray
        |--- public $responseField2='';            // if you set empty string, its main string type
        |
        ---ResponseClass2.php                      // extended from YiiMan\ApiStorm\Response\BaseResponse
        |--- public $responseField1='int';         // you can define one of this data types : int|string|float|serialize|json|array|class|classArray
        |--- public $responseField2='';            // if you set empty string, its main string type
        |
        .
        .
        .
    |
    ---Posts\
       |
       ---PostClass1.php                          // extended from YiiMan\ApiStorm\Post\BasePostData
       |--- public int    $field0;                // Required fields will ends by "0"
       |--- public string $anotherField='test';   // Optional field
       |--- public function rules(): array
                {
                    return
                        [
                            'field'             => 'int',//You should define input field type: int|string|array|float|object
                            'anotherField'      => 'string',
                        ];
                }
       |
       ---PostClass2.php                          // extended from YiiMan\ApiStorm\Post\BasePostData
       |--- public array $field0;                 // Required fields will ends by "0"
       |--- public int   $anotherField=2;         // Optional field
       |--- public function rules(): array
                {
                    return
                        [
                            'field'             => 'float',//You should define input field type: int|string|array|float|object
                            'anotherField'      => 'int',
                        ];
                }
       |
       |
       .
       .
       .
    |
    --- SDKClass.php
    |--- public $protocol = 'https';
    |--- public $baseURl = 'someURL';
    |--- firstMethod(PostClass1 $data):ResponseClass1{
        if ($data->validated()) {

            // you will send $data to your server
            $response = $this->call('path/to/api/url', $data);


            if ($response->isSuccess()) {
                $response = new CreateProductResponse($response);
            }
            // <  Here, you have classified response >
              return $response;
            // </ Here, you have classified response >
        } else {
            return false;
        }
    }
    |
    .
    .
    .
  

用法

第一种方法

克隆项目并检查index.php文件,以查看完整的示例。你可以在控制台中执行index.php以查看结果。

composer install

php index.php

第二种方法

步骤1

为你的SDK创建一个名为TestApi.php的新类

class TestApi
{
    public $protocol = 'https';
    public $baseURl = 'n8.yiiman.ir/webhook';
}

我们需要一个调用方法来连接我们的连接,然后我们需要在调用方法内部配置一个ApiStorm的实例call方法,如下所示

    /**
     * @param  YiiMan\ApiStorm\Post\BasePostData  $dataClass
     * @return YiiMan\ApiStorm\Core\Res
     */
    private function call($path, $dataClass, $method = 'post')
    {
        $servedArrayOfDataClass = $dataClass->serve();
        $connection = new YiiMan\ApiStorm\Core\Connection();
        $connection->baseURL = $this->baseURl;
        $connection->protocol = 'https';

        return $connection->call($path, [], $servedArrayOfDataClass, [],$method);
    }

使用src/examples目录创建新的API SDK

现在我们需要一些方法来在TestApi.php类中使用call来创建连接,如下所示

class TestApi
{
    public $protocol = 'https';
    public $baseURl = 'n8.yiiman.ir/webhook';
    
    
    /**
     * @param  YiiMan\ApiStorm\Post\BasePostData  $dataClass
     * @return YiiMan\ApiStorm\Core\Res
     */
    private function call($path, $dataClass, $method = 'post')
    {
        $servedArrayOfDataClass = $dataClass->serve();
        $connection = new YiiMan\ApiStorm\Core\Connection();
        $connection->baseURL = $this->baseURl;
        $connection->protocol = 'https';

        return $connection->call($path, [], $servedArrayOfDataClass, [],$method);
    }
    
    
    
    /**
     * @param  PostCreateProduct  $product
     * @return CreateProductResponse|bool
     */
    public function createProduct(PostCreateProduct $product)
    {
        if ($product->validated()) {

            // you will send $product to your server
            $response = $this->call('6c81aa91-63a1-43d9-abb6-6b5398716f81', $product,'get');


            if ($response->isSuccess()) {
                $response = new CreateProductResponse($response);
            }

            return $response;
            // </ Here, you will classify response >
        } else {
            return false;
        }
    }

     /**
     * @param  PostCreateProduct  $product
     * @return CreateProductResponse|bool
     */
    public function createProduct2(PostCreateProduct $product)
    {
        if ($product->validated()) {

            // you will send $product to your server
            $response = $this->call('6c81aa91-63a1-43d9-abb6-6b5398716f81', $product);


            if ($response->isSuccess()) {
                $response = new CreateProductResponse($response);
            }

            return $response;
            // </ Here, you will classify response >
        } else {
            return false;
        }
    }
}

步骤2

致谢

特别感谢arianet公司