用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
## 为什么单独创建一个Response? 跟`为什么要单独创建一个Request` 一样。 原因: 可以管理 如: 在 `swoole` 不应该用 `echo`, 因为 `swoole` 是 `cli` 运行,只会输出在命令行。 `必须` 只有一个地方能 `输出响应` 就是此篇的功能 确保有 `集中控制权` 是非常重要 ! (后面代码有 `echo` 都是不规范的, 应该调用 `此篇` 的功能) ## 创建core/Response.php ``` <?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)