Basic use of tp5 controller/tp5 pre-operation/tp5 controller initialization/tp5 empty operation/tp5 jump and redirection

tp5 controller

<?php

namespace app\index\controller;

use think\Controller;

/**
 * Class User
 * @package app\index\controller
 * @author weiyongqiang <[email protected]>
 * 其实tp5中可以不集成Controller但是我们使用了Controller中的方法所以要集成
 */
class User extends Controller
{
    /**
     * @var array
     * 我来定义前置操作,所谓前置操作就是在我配置的操作执行之前执行我
     */
    protected $beforeActionList = [
        'checksession', //在任何操作执行前执行checksession方法
        'islogin' =>  ['except'=>'login'],   //在除login之外的其他方法执行前先执行islogin方法
        'removesession'  =>  ['only'=>'logout'],   //在logout执行前先执行removesession
    ];

    /**
     * @param $name
     * 如果在本控制器中找不到该操作那就运行我
     */
    public function _empty($name)
    {
        echo $name.'这个操作不存在';
    }

    /**
     * 我是控制器初始化方法,执行此控制器的任何操作之前必须先执行我
     */
    public function _initialize()
    {
        Logs::write(time().'访问'.$_SERVER['PHP_SELF']);
    }

    /**
     * @return bool
     * 我是前置操作
     */
    public function checksession()
    {
        return empty(session('USERINFO'));
    }

    /**
     * @return bool
     * 我是前置操作
     */
    public function islogin()
    {
        $userInfo = session('USERINFO');
       return $userInfo.expires > time();
    }


    /**
     * @return bool
     * 我是前置操作
     */
    public function removesession()
    {
        return session('USERINFO', null);
    }

    /**
     * 用户登录操作
     */
    public function login()
    {
        if(用户已经登录了){
            $this->redirect('Home/index', 302);
          //或者使用助手函数
          //redirect('Home/index');
       }

        if(用户信息没有问题){
            $this->success('登录成功', 'Home/index');
       }else{
            $this->success('出错了请稍后再试');

       }
    }

    /**
     * 用户退出操作
     */
    public function logout()
    {
        redirect('Home/index');
    }
}
The knowledge involved in the above example is:
1. Definition
of controller 2. Initialization method of controller: _initialize()
3. Pre-operation: configure protected $beforActionList
4. Jump and redirection: success and error redirection For redirect
5. Empty operation: _empty() is executed when the method you access does not exist

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325787811&siteId=291194637