ThinkPHP使用Base公共控制器redirect()不起作用

ThinkPHP使用Base公共控制器redirect()不起作用

解决在redirect()在继承公共控制器BaseController的Base类中不起作用以及重写initialize方法后出现重定向次数过多的问题

  • Base.php
<?php

namespace app\admin\controller;

use app\BaseController;
use think\App;
use think\exception\HttpResponseException;
use think\facade\Session;

/**
 - Class Base 公共控制器
 */
class Base  extends  BaseController
{

    // 初始化控制器。php 子类 不写默认构造函数, 默认会调用父类构造函数
    public function initialize()
    {
        parent::initialize();

        // 用户未登录重定向到登录界面
        if(empty($this->isLogin())){
            return $this->redirectTo(url('login/index'));
        }
    }

    /**
     * 判断用户是否登录
     * @return bool
     */
    public function isLogin()
    {
        $userInfo = Session::get('userInfo');
        // 用户未登录返回 false
        if(empty($userInfo)){
            return false;
        }

        // 用户已登录返回 true
        return true;
    }

    /**
     * 自定义重定向方法
     * @param $args
     */
    public function redirectTo(...$args)
    {
        // 此处 throw new HttpResponseException 这个异常一定要写
        throw new HttpResponseException(redirect(...$args));
    }
}
  • Login.php
<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\Request;

/**
 * Class Login 后台登录
 */
class Login extends Base
{
    public function initialize() {
        // 用户若已经登录,则重定向到首页 解决循环重定向
        if($this->isLogin()) {
            return $this->redirectTo(url('index/index'));
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值