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'));
}
}
}