preface

Sw-x Framework – A PHP-Swoolex framework that focuses on high performance and easy development

I hope you raise your hands and give me a star: github.com/swoolex/swo…

1. Configure interface 404

In the HTTP service, if the route cannot be found, the server loads 404 in the /config/route. PHP configuration file.

Specific configuration items are as follows:


      
return [
    // Whether to enable custom error handlers when routes cannot be found
    '404'= >true.// A custom error handler that only needs to provide the namespace location of a class
    'error_class'= >'\\box\\http_error',];Copy the code

Open the /box/http_error. PHP file and change it to the following code:


      
namespace box;
use \x\controller\Http;

class http_error  extends Http{

    /** * entry *@todoNo *@authorSmall cattle *@versionV1.0.1 + 2020.05.29 *@deprecated* is not enabled@globalNo *@return void
    */
    public function __construct() {
        return\x\Restful::code(\x\Restful::ONROUTE())->callback(); }}Copy the code

Because the \x\Restful component above throws an ONROUTE status code, the corresponding Restful configuration also needs to be modified:

/ restful/default/code. PHP modified into the following code:


      
return [
    'ERROR'= >0.// Default failure status code
    'SUCCESS'= >1.// Default success status code
    'ACTION_ERROR'= >40001.// Permission verification failed
	'ONROUTE'= >40004.// Interface does not exist
];
Copy the code

/restful/default/msg. PHP


      
return [
    // Default error status code corresponding to tips
    'ERROR'= > ['default'= >'Request failed'./ / the default value].// Default tips corresponding to the success status code
    'SUCCESS'= > ['default'= >'Request successful'./ / the default value
		'test'= >'test MSG',].// Permission verification failed
    'ACTION_ERROR'= > ['default'= >'Permission verification failed'./ / the default value].// Interface does not exist
    'ONROUTE'= > ['default'= >'This interface does not exist'./ / the default value]];Copy the code

Access a nonexistent interface at http://IP: port/API /user/info, and the framework throws the following status code:

{"code": 40004, "MSG ":" this interface does not exist ", "data": []}Copy the code

2. Request type restriction

There are several ways in SW-X that you need to restrict the type of request a particular HTTP controller can make,

The first is to restrict it with @POST, @get, and @Ajax annotations.

The second method uses the \x\Validate validator component to filter the request headers.

The first method is recommended because it is very flexible, while the second method is generally used when some interfaces in the same group need the same request header filtering, such as signature judgment.

Below, we will/app/HTTP/v1_0_1 / controller/shop/delete. PHP controller to change the HTML code is as follows:


      
namespace app\http\v1_0_1\controller\shop;
use x\controller\Http;
// Import Restful components
use x\Restful;

class delete extends Http
{
    /** * I only allow Post+Ajax requests *@Post
     * @Ajax* /
    public function index() {
		// Restful components throw interface responses
		return Restful::code(Restful::SUCCESS())->data('Your request has been approved')->callback(); }}Copy the code

Also, since the error message in this annotation is handled by the callback from the /box/lifecycle/route_error.php lifecycle file, we also need to change this file to the following code:


      
namespace box\lifecycle;

class route_error
{
    /** * specifically convert the Msg value of the 3 annotations */
    private $tips = [
        'Route Method Get'= >'Only Get requests are allowed'.'Route Method Post'= >'Post requests only'.'Route Method Ajax'= >'Ajax requests only',];/** * accept callback processing *@todoNo *@authorSmall cattle *@versionV1.1.5 + 2020.07.15 *@deprecated* is not enabled@globalNo *@paramSwoole $server service instance *@paramString $fd Client identifier *@paramString $status Error event status code *@return bool
    */
    public function run($server.$fd.$status) {
        $tips = 'Annotate: sw-x Status: '.$status.'the ERROR! ';

        $type = \x\Config::get('server.sw_service_type');
        // Only HTTP service requests are thrown
        if ($type= ='http') {
            if (isset($this->tips[$status])) $tips = $this->tips[$status];
            return \x\Restful::code(\x\Restful::LIFECYCLE())->setMsg($tips)->callback();
        }
        return true; }}Copy the code

LIFECYCLE status will need to be changed due to the use of the \x\Restful component.

/ restful/default/code. PHP modified into the following code:


      
return [
    'ERROR'= >0.// Default failure status code
    'SUCCESS'= >1.// Default success status code
    'ACTION_ERROR'= >40001.// Permission verification failed
	'ONROUTE'= >40004.// Interface does not exist
    'LIFECYCLE'= >20001.// Route lifecycle error callback status code [use custom MSG]
];
Copy the code

Note that after the life cycle file is modified, hot overloading is invalid and you need to manually stop and restart the service.

After the restart, we can visit http://IP: port/API /shop/delete interface and see that the framework throws the following status code:

{"code": 20001, "MSG ":" Post request only ", "data": []}Copy the code

To test the success of the request, you can simply send a post-Ajax request using a tool like Postman or Jquery.

3. Validate form data

Sw-x is recommended to use the \ X \Validate validator component to filter requests.

For details, please refer to the official document https://www.sw-x.cn/word/v2.5.x/vali_explain.html

Let’s create a Shop validator for API requests for grouping items.

Create the validator file /box/validate/ shop.php with the following code:


      
namespace box\validate;
use x\Validate;

class Shop extends Validate
{
    // Define rules for fields
    protected $rule = [
        'id'= >'require|int'.'title'= >'require|min:10|max:20'.'info.des'= >'min:10|max:20',];// Custom error value declarations
    protected $message  =   [
        'id.require'= >'{id} forgot to enter '.'title.min'= >'{title} must not be less than {0}'.'title.max'= >'{title} cannot be greater than {0}'.'info.des.min'= >'{: Preset} cannot be less than {0}'.'info.des.min'= >'{info.des} cannot be greater than {0}',];// Scene definition
    protected $scene = [
        // Scenario used for modification (short)
        'edit'= > ['id'.'info.des'].// Field to verify
        // Scenario used when deleting (short)
        'delete'= > ['id'].// Field to verify
    ];
}
Copy the code

Below, we will/app/HTTP/v1_0_1 / controller/shop/delete. PHP controller to change the HTML code is as follows:


      
namespace app\http\v1_0_1\controller\shop;
use x\controller\Http;
// Import Restful components
use x\Restful;

class delete extends Http
{
    /** * Bind validator * with annotations@Validate(class="\box\validate\Shop", scene="delete")
    */
    public function index() {
		// Restful components throw interface responses
		return Restful::code(Restful::SUCCESS())->data('Check passed')->callback(); }}Copy the code

Also, since the error message in this annotation is handled by the callback from the /box/lifecycle/validate_error.php lifecycle file, we need to change this file to the following code:


      
namespace box\lifecycle;

class validate_error
{
    /** * accept callback processing *@todoNo *@authorSmall cattle *@versionV2.5.6 + 2021-09-15 *@deprecated* is not enabled@globalNo *@paramString $server_type Service type HTTP /websocket/ RPC/MQTT *@paramBool $Batch Specifies whether to filter all *@paramArray $errors Error verification result set *@return bool
    */
    public function run($server_type.$batch.$errors) {
        // $batch is used to execute all the filtering rules, and then returns all the error causes together
        // The default life cycle returns only the first reason for the error
        $error = $errors[0] ['intact_field'].'= >'.$errors[0] ['message'];

        // Only HTTP service requests are thrown
        if ($server_type= ='http') {
            return \x\Restful::code(\x\Restful::VALIDATE())->setMsg($errors[0] ['message'])->callback();
        }
        return true; }}Copy the code

Due to the above use \ \ x Restful components, throws a VALIDATE status code, so the corresponding Restful configuration should also be modified:

/ restful/default/code. PHP modified into the following code:


      
return [
    'ERROR'= >0.// Default failure status code
    'SUCCESS'= >1.// Default success status code
    'ACTION_ERROR'= >40001.// Permission verification failed
	'ONROUTE'= >40004.// Interface does not exist
    'LIFECYCLE'= >20001.// Route lifecycle error callback status code [use custom MSG]
    'VALIDATE'= >20002.// Validator lifecycle error callback status code [use custom MSG]
];
Copy the code

Note that after the life cycle file is modified, hot overloading is invalid and you need to manually stop and restart the service.

After the restart, we can visit http://IP: port/API /shop/delete interface and see that the framework throws the following status code:

{"code": 20002, "MSG ": "data": []}Copy the code

Visit http://IP address: port/API /shop/delete? If id=1, the verification scenario for delete can be passed.