-- 创造无限可能

thinkphp6bug:构造方法无法使用redirect()重定向问题

2022-05-03 00:40:16
355 人浏览 10 人点赞
有用,点赞支持一下

场景:在做角色权限或者登录的时候我们需要判断是否登录,但thinkPHP6在基类构造方法无法使用redirect方法重定向。
原因:redirect()返回的是\think\response\Redirect对象,而此对象被app\BaseController类中的构造方法所获取。
解决:自定义重定向方法

 /**
     * 自定义重定向方法
     * @param $args
     */
    public function redirectTo(...$args)
    {
        // 此处 throw new HttpResponseException 抛出异常重定向
        throw new HttpResponseException(redirect(...$args));
    }
    // 使用
    return $this->redirectTo((string)url('admin/Login/index'));