在非 laravel 项目中使用 laravel 的特性 9: Http Request && Response

http Request && Response

安装所需要的包

composer require guzzlehttp/guzzle
composer require illuminate/http

文档,重点关注 Request 和 Response

使用示例

<?php

use Illuminate\Http\Client\Factory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

require_once __DIR__ . '/../vendor/autoload.php';
date_default_timezone_set('UTC');

$http = new Factory();

//$response = $http->post('https://jsonplaceholder.typicode.com/posts', [
//    'title' => 'foo',
//    'body' => 'bar',
//    'userId' => 1,
//]);
//$id = $response->json()['id'];
//
//$response = $http->get('https://jsonplaceholder.typicode.com/posts');
//echo $response->body();

// http://localhost:8000/index/http.php?name=Chrome&type=1&from=browser
// 需要项目入口文件是 index.php 且请求路径隐藏 例如:http://localhost:8000?name=Chrome&type=1&from=browser
$request = new Request();
$name = $request->input('name', 'Joey');
mm($name);
mm($request->has('name'));
mm($request->all());
mm($request->path());
mm($request->url());
mm($request->fullUrl());
mm($request->method());
mm($request->isMethod('get'));

$response = new Response();
$response->setContent(['name' => $name])->setStatusCode(200)->send();

命令行开启服务 php -S localhost:8000 并访问 http://localhost:8000/index/http.php 即可。

todo

封装 api 返回

参考 致谢

  1. mattstauffer/Torch
  2. 教你更优雅地写 API 之「规范响应数据」
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!