t6接口返回与跳转

tp6不再提供基础控制器类think\Controller,原来的success、error、redirect和result方法需要自己在基础控制器类里面实现,跳转可以安装扩展,也可以自己在控制器写

composer require liliuwei/thinkphp-jump

安装之后在控制器中调用

use \liliuwei\think\Jump;
 
use Jump;

不过这种方法在写接口时候不怎么好用,最后还是自己来写了

 
    protected function success($msg = 'ok',$data = '', $type = '', array $header = [])
    {
        $result = [
            'code' => 1,
            'msg' => $msg,
            'time' => time(),
            'data' => $data,
        ];

        $type = $type ?: $this->getResponseType();
        $response = Response::create($result, $type)->header($header);

        throw new HttpResponseException($response);
    }

    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($data, $code, $msg, $type, $header);
    }

  
     protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => time(),
            'data' => $data,
        ];

        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }

        $type = $type ?: $this->getResponseType();
        $response = Response::create($result, $type,$code)->header($header);

        throw new HttpResponseException($response);
    }


    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType()
    {
        // return $this->request->isJson() || $this->request->isAjax() || $this->request->isPost() ? 'json' : 'html';
         return  'json';
    }


posted @ 2020-10-18 11:48  Twoknives_li  阅读(292)  评论(0)    收藏  举报