astronphp / http
0.1.1
2019-12-17 11:55 UTC
Requires
- php: ^7.0
- astronphp/collection: ^0
Requires (Dev)
README
安装
composer require astronphp/http
用户指南
1. 发送请求
1.1 初始配置
use \Astronphp\Http\Request; $request = new Request('www.example.com/api');
1.2 发送请求
$request->post('/users'); $request->get('/users/1'); $request->put('/users/1'); $request->patch('/users/1'); $request->delete('/users/1');
1.3 发送一个头部
use \Astronphp\Http\Header; $header = new Header(); $header->add('Content-Type', 'application/json'); // ou usando constantes // $header->add(Header::CONTENT_TYPE, Request::JSON); $request->get('/users/1', $header);
1.4 发送一个体
use \Astronphp\Http\Header; use \Astronphp\Http\Body; $header = new Header(); $header->add('Content-Type', 'application/json'); // $header->add('Content-Type', 'multipart/form-data'); // $header->add('Content-Type', 'application/x-www-form-urlencoded'); // baseado no Content-Type, o objeto $body saberá como os dados devem ser enviados. $body = new Body(); $body->set('name', 'Lorem Ipsum'); $body->set('document', '123.456.789-12'); $request->post('/users', $header, $body);
1.5 通过 URL 发送参数
$request->set('department', 'clothing'); $request->set('sort', 'best_seller'); // www.example.com/api/products/clothing?sort=best_seller $request->get('/products/{department}');
也可以提供一个关联数组,这会产生与上一个示例相同的结果。
$request->set(['department' => 'clothing', 'sort' => 'best_seller']); $request->get('/products/{department}');
1.6 接收响应数据
假设以下示例返回以下结构
{ "status": "success", "data": { "id": 1, "name": "Astron", "username": "astronphp", "password": "@astronphp" } }
$response = $request->get('/users/1'); $response->getHttpCode(); // 200 $response->get('status'); // success $response->get('data.name'); // Astron
2. 接收请求
2.1 初始配置
use \Astronphp\Http\Request; $request = new Request();
2.2 访问数据
$request->query('username'); // dados recebidos via get $request->body('username'); // dados recebidos via post $request->files('picture'); $request->server('request_uri'); // case insensitive $request->header('content_type'); // case insentitive
3. 发送一个响应
3.1 初始配置
use \Astronphp\Http\Response; $response = new Response(['status' => 'success', 'message' => 'lorem ipsum']); // ou como uma string json // $response = new Response({"status":"success", "message":"lorem ipsum"});
3.2 发送 JSON 响应
$response->json();
4. 页面间导航
4.1 配置基本 URI
\Astronphp\Http\Location::setBaseUri('https://www.example.com');
4.2 重定向
$location = new \Astronphp\Http\Location('/products'); $location->redirect(); // redireciona para https://www.example.com/products
4.3 重新加载页面
$location = new \Astronphp\Http\Location(); $location->reload();