Home  >  Article  >  PHP Framework  >  How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

藏色散人
藏色散人forward
2022-01-13 11:09:102572browse

The followingthinkphp frameworktutorial column will introduce to you the process of using ThinkPHP5.1 middleware in the controller. I hope it will be helpful to friends in need!

ThinkPHP5.1 middleware usage process in the controller

The beginning of using middleware and my step description, I hope it can help Those of you who have just learned PHP or just learned the think framework hope to communicate with you and make progress.

I already understand the role of middleware in the Thinkphp framework. It is the header generated when the user accesses resources or the post input when the user requests parameters before the request reaches the application layer. Or get or other request types, and url path operations, including pre- or post-operation or execution order and other solutions. After understanding it, I feel that this thing is very useful in processing user request data, which is much better than processing it directly in the controller or in the behavior. (So ​​I read the 5.1 documentation manual with full excitement).

After reading the document, follow the official manual method and type the following code on the command line:
php think make:middleware Check
The meaning of this code is to produce a Middleware directory and create a new middleware file named Check
The content is completed normally without any problem

The 5.1 document code is pasted according to the document requirements

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

Copied exactly according to the manual, there are no problems, confirm the saving and any errors.

I confirm that a file named middleware.php is placed in the root directory of my admin module as shown below

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

, just like this A registration, then if you want to use middleware under this module, you can use it.

Then I added the code as shown in the picture in the controller according to the content in the documentation manual and the description of the controller middleware content

How is TP5.1 middleware used in the controller? (Detailed explanation of the process),

It turned out that the code was not executed. I scratched my head in confusion. According to my understanding, if I did this, it should be applied directly. The result object was empty. In desperation, according to my own understanding, I stopped the code in the middleware

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

After seeing what I wanted to see , test my $request again. I saw what I had been looking forward to for a long time, my middleware is ready

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

The above steps tell me so far , the first step has been completed, I can now use a middleware to do what I want to do

The first step is to change the name to what I want. There are three changes here.
How is TP5.1 middleware used in the controller? (Detailed explanation of the process)
How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

After refreshing again, I found that it can still be used, and it runs absolutely smoothly. In this step, I also firmed up some of my usage ideas, such as creating multiple middlewares. Each controller should have a corresponding one. I can perform some of my own processing here. You can also use it after reading the manual. Various other methods, including changes in the order of execution, make me wonder. From now on, the code can become a little taller again.

The second step is to establish functional rules to cooperate with the self-built files in the Config configuration to control access

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)##

How is TP5.1 middleware used in the controller? (Detailed explanation of the process)

<?php namespace apphttpmiddleware;
use thinkfacadeConfig;
use thinkfacadeRequest;
/**
登陆接口通用数据配置检测*/
class AdminLoginCheck
{
/**
 * handle  重写处理请求对象的操作函数
 * @param  object Request $request 请求对象
 * @param  object \Closure $next 响应对象
 * @return array 错误返回的信息
 *         code 返回码
 *         msg 返回信息
 *         data 返回数据
 * @return  object 响应对象
 */
public function handle($request, \Closure $next)
{
    // 检测配置,查看该接口服务是否被暂停使用
    if (true !== Config::get(Request::module().&#39;.&#39;.Request::action().&#39;.&#39;.Request::action().&#39;_api&#39;))
    // 如果结果不符合要求则返回错误信息
    exit(json_encode([&#39;code&#39;=>1,'msg'=>'Interface_Pause_service','data'=>'']));
    // 检测配置,是否执行请求验证类型
    if (false !== Config::get(Request::module().'.'.Request::action().'.'.Request::action().'_request'))
    {

        // 登陆请求规则,传入相应方法,查看该接口是否符合请求类需
        $res = self::loginRequestRole(Request::action());
        // 如果结果不符合要求则返回错误信息
        if (true !== $res) exit(json_encode(['code'=>1,'msg'=>'Request_Type_Not_Matching','data'=>'']));
    }
    // 检测配置,是否执行地址限制验证
    if (false !== Config::get(Request::module().'.'.Request::action().'.'.Request::action().'_address'))
    {
        // 客户端访问地址限制请求规则
        $res = self::loginAddressDispose(Request::ip());
        // 如果结果不符合要求则返回错误信息
        if (true !== $res) exit(json_encode(['code'=>1,'msg'=>'Address_Not_Access','data'=>'']));
    }
    // 格式化与处理前台参数
    $request = self::loginParamDispose(Request::action(),$request);
    
    // 继续执行进入到控制器
    return $next($request);
}

/**
 * loginRequestRole 请求类型验证
 * @param  string $scene 根据路径传入方法名称
 * @return bool 验证用户访问的接口是否符合预设的请求要求
 */
protected static function loginRequestRole($scene)
{
    switch ($scene)
    {
        // 登陆页面请求验证
        case 'index':
            if (Request::isGet()) return true;
            else return false;
            break;
        // 登陆接口请求验证
        case 'login':
            if (Request::isPost() || Request::isAjax() || Request::isPjax()) return true;
            else return false;
            break;
        // 登陆接口请求验证
        case 'resetPassword':
            if (Request::isPost() || Request::isAjax() || Request::isPjax()) return true;
            else return false;
            break;
        // 默认验证或者不存在的场景返回
        default:
            return false;
            break;
    }
}

/**
 * loginAddressDispose 地址是否允许访问
 * @param  string $address 需要传入一个address地址
 * @return string     返回错误信息
 * @return bool     检测正确返回真
 */
protected static function loginAddressDispose($address)
{
    // 读取配置内的设置参数
    $data = Config::get(Request::module().'.'.Request::action().'.'.Request::action().'_address_data');
    // 如果配置信息address列表为空则返回不能访问
    if (empty($data)) return false;
    // 循环地址列表信息解开连续address地址列表
    foreach ($data as $key => $val) { if ($val == $address) return true; }
    // 如果继续执行下去依然没有 返回不能访问
    return false;
}

/**
 * loginParamDispose post内容与格式处理
 * @param  string $scene 需要前往的接口名称
 * @param  object $request 请求的对象内容
 * @return object 返回处理过的请求对象
 */
protected static function loginParamDispose($scene,$request)
{
    switch ($scene)
    {
        // 登陆页面
        case 'index':
            break;
        // 登陆接口请求参数处理
        case 'login':
            // 前台用户传入的参数进行调整转换
            $request->username = $request->param('user');
            $request->password = $request->param('pass');
            $request->captcha = $request->param('code');
            // 对记住我进行处理
            $remember = $request->param('remember');
            if (null === $remember) $request->remember = 'shut';
            else $request->remember = 'open';
            break;
        // 重置密码接口参数处理
        case 'resetPassword':
            // 前台用户传入的参数进行调整转换
            $request->username = $request->param('user');
            $request->phone = $request->param('mobile');
            $request->phonecode = $request->param('code');
            $request->password = $request->param('pass');
            $request->repassword = $request->param('repass');
            break;
        // 默认接口或者不存在的场景返回
        default:
            break;
    }
    return $request;
}
}

At this point, a simple middleware detection work is completed. Of course, this writing method is subject to fixed requirements, such as the unification of interfaces in multiple control accesses. Bring the api request with the request so that it can be used normally no matter what.

The two separate issues to be mentioned are that you can actually continue to use the content that needs to be used in the configuration

The first problem is that middleware is not omnipotent. It can only do some request processing, and it must take parameters. Never do advanced verification that does not meet the requirements. The most important thing here is to do some pre-verification to let the data Safe or full of data

The second problem is don’t try to do inappropriate actions in the middleware, don’t execute super complex code in the middleware, if you use the middleware to do super complex code or super I estimate that long operations can kill many people. What I mentioned here includes using as little as possible the function code defined by your own function library to verify that some unavoidable code can still be used, such as password encryption and similar codes

The above is the detailed content of How is TP5.1 middleware used in the controller? (Detailed explanation of the process). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete