PHP builds a high-performance API architecture based on SW-X framework

Posted by Bidibule on Tue, 01 Mar 2022 05:03:59 +0100

preface

Official website address: SW-X framework - PHP swoolex framework focusing on high-performance and convenient development

I hope the big guys raise their hands and give my little brother a star: https://github.com/swoolex/swoolex

1. What is Restful component

In SW-X, Restful component is the encapsulation support of API return value structure.
\The x\Restful class supports defining the structure of the return value, code - > MSG Association, strong type conversion of the return value, conversion of the thrown data type, and definition of the response request header (cross domain support).

2. Restful settings

The use of API return value mainly depends on config. In the / restful / directory PHP configuration item. The initialization default configuration is as follows:

<?php
return [
    // The return value type supports json|xml
    'type' => 'json',
    // Default return value format
    'default' => [
         'force'  => true, // Whether to force the return value int|double|null type conversion
         'status' => 'code', // Status code field name
         'tips'   => 'msg',  // Description field name
         'result' => 'data', // Result set field name
         'set'    => [], // Default result set
         'headers' => [], // Response header, which can be used for cross domain settings (supported before v2.5.23)
    ],
]

Default is the default data structure. When we do not use \ x\Restful::make('New subscript ') to specify a new return value structure, this structure is used by default. If we need to set a new return value structure, we only need to copy the array structure of default and change the subscript to a new value.

At the same time, there is also a default directory under the / restful / directory. This directory is the default return value structure corresponding to default, which is used to store code status code and msg status description.

If a new data structure is set, you need to copy the default directory and rename it to the corresponding subscript name.

Let's look at two files in the default directory:

Code status code, / restful / default / code php:

<?php
// Status code management
return [
    'ERROR' => 0, // Default failure status code
    'SUCCESS' => 1, // Default success status code
];

In practical application, we only need to read the corresponding status code value through \ x\Restful:: status code key name (). For example, use \ x\Restful::SUCCESS() for the status code of SUCCESS.

Description, / Msg / default php:

<?php
// Status description management
return [
    // tips corresponding to the default error status code
    'ERROR' => [
        'default' => 'request was aborted', // Default value
    ],
    // tips corresponding to the default success status code
    'SUCCESS' => [
        'default' => 'Request succeeded', // Default value
        'test' => 'test msg',
    ],
];

The status code description is a two-dimensional array. The one-dimensional subscript needs to correspond to the subscript of the status code, and there must be a two-dimensional subscript named default.

The original intention of this design is that in practical application, there may be multiple different descriptions of the same status code, so you can read the corresponding description by specifying the subscript. If not specified, read the default subscript.

For example:

use x\Restful;

// Read the SUCCESS['default '] description. Default is used by default
Restful::code(Restful::SUCCESS())->callback();

// Specify the msg subscript and read the SUCCESS['test '] description
Restful::code(Restful::SUCCESS())->msg('test')->callback();

3. More examples of Restful components

use x\Restful;

// Customize msg content
return Restful::code(Restful::SUCCESS())->setMsg('Threw me out, didn't use it msg.php Configuration in')->callback();

// Custom throw type
return Restful::type('xml')->code(Restful::SUCCESS())->callback();

// Set the data set thrown
return Restful::code(Restful::SUCCESS())->data([
    'user_id' => 1,
    'username' => 'SW-X',
])->callback();

// Set up cross domain support
return Restful::code(Restful::SUCCESS())->header([
    // Interface cross domain settings
    'origin' => '*',
    // Interface data request type
    'type' => '',
    // The type of request allowed by the interface across domains
    'methods' => 'POST,GET,OPTIONS,DELETE',
    // Whether the interface allows sending cookies
    'credentials' => 'true',
    // Interface allows you to customize the fields of the request header
    'headers' => 'Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin, api_key',
])->callback();

4. A simple example of using Restful in a controller

Back to the previous article, we modified shop / select Controller code corresponding to PHP route:

<?php
namespace app\http\v1_0_1\controller\shop;
use x\controller\Http;
// Introducing Restful components
use x\Restful;

class select extends Http
{
    public function index() {
        // Restful component throws interface response
        return Restful::code(Restful::SUCCESS())->data([
            'user_id' => '1',
            'username' => 'SW-X',
        ])->callback();
    }
}

Output result:

{
  "code": 1,
  "msg": "Request succeeded",
  "data": {
    "user_id": 1,
    "username": "SW-X"
  }
}

5. Enumeration

If you are not used to Restful component style management API interface return value, SW-X also supports Enum enumeration definition.

The enumeration class must inherit from the \ design\Enum base class. It is officially recommended to uniformly define it in the / box/enum / directory, but it is not mandatory.

Let's create a ShopEnum class under this directory. The code is as follows:

<?php
namespace box\enum;
// Must inherit enum base class
use design\Enum;

class ShopEnum extends Enum {
    /*
     * Error exception
    */
    const ERROR = 500;
    /**
     * Normal request
    */
    const SUCCESS = 200;
}

Note the above annotation style. The annotation content is the MSG content corresponding to the status code.

6. Use examples of enumeration classes

use box\enum\ShopEnum;
// Get the corresponding Msg content
echo ShopEnum::get(ShopEnum::ERROR);

// Assembled into an array structure of code MSG data (the three field names are fixed by the system)
ShopEnum::get(ShopEnum::ERROR, [
    'data' => [
        'user_id' => 1
    ]
]);
Result set:
array(3) {
  ["code"]=>
  int(500)
  ["msg"]=>
  string(12) "Error exception"
  ["data"]=>
  array(1) {
    ["user_id"]=>
    int(1)
  }
}

// Custom data structure:
$ret = [
    'code' => ShopEnum::ERROR,
    'msg' => ShopEnum::get(ShopEnum::ERROR),
    'data => [],
];

7. A simple example of using enumeration in a controller

Back to the previous article, we modified shop / select Controller code corresponding to PHP route:

<?php
namespace app\http\v1_0_1\controller\shop;
use x\controller\Http;
// Introducing custom enumeration classes
use box\enum\ShopEnum;

class select extends Http
{

    public function index() {
        $array = ShopEnum::get(ShopEnum::ERROR, [
                'data' => [
                'user_id' => 1
            ]
        ]);
        return $this->fetch(dd($array));
    }
}

Output result:

array(3) {
  ["code"] => int(500)
  ["msg"] => string(12) "Error exception"
  ["data"] => array(1) {
    ["user_id"] => int(1)
  }
}

Topics: PHP RESTful swoole