使用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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值