五十、逐行阅读Yii2.0.43_Yii框架文件yii\web\Response.php(2)

一、init方法,组件初始化

    //组件初始化
    public function init()
    {
        // http版本
        if ($this->version === null) {
            if (isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL'] === 'HTTP/1.0') {
                $this->version = '1.0';
            } else {
                $this->version = '1.1';
            }
        }

        // 字符集
        if ($this->charset === null) {
            $this->charset = Yii::$app->charset;
        }

        //内容格式
        $this->formatters = array_merge(
            $this->defaultFormatters(),
            $this->formatters
        );
    }

二、getStatusCode方法,http响应状态码

    // http响应状态码
    public function getStatusCode()
    {
        return $this->_statusCode;
    }

三、setStatusCode方法,设置响应状态码

    // 设置响应码
    public function setStatusCode($value, $text = null)
    {
        // 默认状态码 200, OK
        if ($value === null) {
            $value = 200;
        }

        // 检查$value是否合法
        $this->_statusCode = (int) $value;
        if ($this->getIsInvalid()) {
            throw new InvalidArgumentException("The HTTP status code is invalid: $value");
        }

        // 状态文本描述
        if ($text === null) {
            $this->statusText = isset(static::$httpStatuses[$this->_statusCode]) ?
                static::$httpStatuses[$this->_statusCode] :
                '';
        } else {
            $this->statusText = $text;
        }

        return $this;
    }

四、setStatusCodeByException方法,设置响应码根据异常

    // 根据异常设置响应状态代码
    public function setStatusCodeByException($e)
    {
        if ($e instanceof HttpException) {
            // 将异常码作为响应码
            $this->setStatusCode($e->statusCode);
        } else {
           // 默认异常500
            $this->setStatusCode(500);
        }

        return $this;
    }

五、getHeaders方法,返回HeaderCollection实例

    // 返回HeaderCollection实例
    public function getHeaders()
    {
        if ($this->_headers === null) {
            $this->_headers = new HeaderCollection();
        }

        return $this->_headers;
    }

总结:

 阅读了5个方法:

  • init方法,组件初始化
  • getStatusCode方法,http响应状态码
  • setStatusCode方法,设置响应状态码
  • setStatusCodeByException方法,设置响应码根据异常
  • getHeaders方法,返回HeaderCollection实例
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值