使用Composer从零开发一个简单的restful框架(03)-封装http请求和响应
新建core/Request.php
,内容如下
<?php
namespace core;
class Request {
private string $method; //请求方法
private string $uri; //请求路径
private array $queryParams; //get 数据
private array $postData; //post 数据
private array $params = []; //路由参数
public function __construct() {
$this->method = $_SERVER['REQUEST_METHOD'];
$this->uri = $_SERVER['REQUEST_URI'];
$this->queryParams = $_GET;
$this->postData = $_POST;
}
public function getMethod(): string {
return $this->method;
}
public function getUri(): string {
return explode('?', $this->uri, 2)[0];
}
public function getQueryParams(): array {
return $this->queryParams;
}
public function getPostData(): array {
return $this->postData;
}
public function getParams(): array {
return $this->params;
}
public function setParams(array $val): void {
$this->params = $val;
}
public function getParam(string $key) {
return $this->params[$key];
}
}
新建core/Response.php
,内容如下
<?php
namespace core;
class Response {
private int $statusCode = 0; //状态码
private array $headers = []; //http 请求头
private string $body; //返回数据
public function addHeader($name, $value): void {
$this->headers[$name] = $value;
}
public function text($body): void {
$this->statusCode = 200;
$this->body = $body;
}
public function json($val): void {
$this->statusCode = 200;
$this->body = json_encode($val);
$this->addHeader('Content-Type', 'application/json');
}
public function abort($body = ''): void {
$this->statusCode = 200;
$this->body = $body;
}
public function abortWithCode(int $code, $body = ''): void {
$this->statusCode = $code;
$this->body = $body;
}
public function send(): void {
if (!$this->statusCode) {
$this->statusCode = 404;
$this->body = '404 NOT FOUND';
}
http_response_code($this->statusCode);
foreach ($this->headers as $name => $value) {
header("$name: $value");
}
echo $this->body;
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接