Thinkphp5及Thinkphp6 调用后台方法前判断是否登录

Thinkphp5及Thinkphp6 调用后台方法前判断是否登录 ,老年人记忆系列,记不住就copy一下提高效率

_initialize()方法解释

tp5 _initialize()

<?php
namespace app\admin\controller;
use app\admin\model\Role;
use think\Controller;
use think\Request;
use think\Session;
use think\Cache;

class Base extends Controller
{
    //初始化方法,相当于析构方法
    protected function _initialize(){
        $enable=array('Login/index',"Login/tologin");
        $request= \think\Request::instance();
        $controller = $request->controller();
        $action = $request->action();
        $path=$controller.'/'.$action;
        if(!in_array($path,$enable)){
            $user=$this->user_info();
        }
    }
     //判断用户是否存在
    public function user_info(){
        if(Session::has('user_info')){
            $rs = Session::get("user_info");
            $post = Role::where(array("r_id"=>$rs['roles_id']))->find();
            $rs['post'] = $post['r_name'];
            return $rs;
        }else{
           echo "<script>location.href='".url('Login/index')."';</script>";
           exit();
        }
    }
   
}

tp5.1 initialize()

<?php
namespace app\admin\controller;
use app\admin\model\Role;
use think\Controller;
use think\facade\Session;
use think\facade\Request;
class Base extends Controller
{
    //初始化方法,相当于析构方法
    protected function initialize(){
        $enable=array('Login/index',"Login/tologin");
        $controller = Request::controller();
	$action = Request::action ();
        $path=$controller.'/'.$action;
        if(!in_array($path,$enable)){
            $user=$this->user_info();
        }
    }
    
     //判断用户是否存在
    public function user_info(){

        if(Session::has('user_info')){
            $rs = Session::get("user_info");
            $post = Role::where(array("r_id"=>$rs['roles_id']))->find();
            $rs['post'] = $post['r_name'];
            return $rs;
        }else{
           echo "<script>location.href='".url('Login/index')."';</script>";
           exit();
        }
    }
    
}

tp6 initialize()

<?php
namespace app\admin\controller;
use app\admin\model\Role;
use think\facade\Request;
use think\facade\Session;
use app\BaseController;
class Base extends BaseController
{
    //初始化方法,相当于析构方法
    protected function initialize(){
        
        $enable=array('Login/index',"Login/tologin");
        $controller = Request::controller();
        $action = Request::action ();
        $path=$controller.'/'.$action;
        if(!in_array($path,$enable)){
            $user=$this->user_info();
        }
    }
    
     //判断用户是否存在
    public function user_info(){

        if(Session::has('user_info')){
            $rs = Session::get("user_info");
            $post = Role::where(array("r_id"=>$rs['roles_id']))->find();
            $rs['post'] = $post['r_name'];
            return $rs;
        }else{
           echo "<script>location.href='".url('Login/index')."';</script>";
           exit();
        }
    }
   
}
0 评论
内联反馈
查看所有评论