php response响应,9. 响应 (Response)

## 为什么单独创建一个Response?

跟`为什么要单独创建一个Request` 一样。

原因: 可以管理

如: 在 `swoole` 不应该用 `echo`, 因为 `swoole` 是 `cli` 运行,只会输出在命令行。

`必须` 只有一个地方能 `输出响应` 就是此篇的功能

确保有 `集中控制权` 是非常重要 !

(后面代码有 `echo` 都是不规范的, 应该调用 `此篇` 的功能)

## 创建core/Response.php

```

namespace core;

class Response

{

protected $headers = []; // 要发送的请求头

protected $content = ''; // 要发送的内容

protected $code = 200; // 发送状态码

public function sendContent() // 发送内容

{

echo $this->content;

}

public function sendHeaders() // 发送请求头

{

foreach ($this->headers as $key => $header)

header($key.': '.$header);

}

public function send() // 发送

{

$this->sendHeaders();

$this->sendContent();

return $this;

}

public function setContent($content) // 设置内容

{

if( is_array($content))

$content = json_encode($content);

$this->content = $content;

return $this;

}

public function getContent() // 获取内容

{

return $this->content;

}

public function getStatusCode() // 获取状态码

{

return $this->code;

}

public function setCode(int $code) // 设置状态码

{

$this->code = $code;

return $this;

}

}

```

## 在容器绑定Response类

编辑 `app.php`的`register` 方法

![](https://img.kancloud.cn/f0/ad/f0ad878555ff9efa213a1c6011f7c17e_606x187.png)

## 编辑index.php

![](https://img.kancloud.cn/56/90/5690de0edbfdf9f0665cdaf48566e739_824x519.png)

![](https://img.kancloud.cn/06/3b/063bb94f40ec4253318fc802cdfef561_612x175.png)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值