neat / http
Neat HTTP 组件
0.6.3
2020-01-14 08:04 UTC
Requires
- php: >=7.0
- psr/http-message: ^1.0
Requires (Dev)
- guzzlehttp/psr7: ^1.6
- phpunit/phpunit: ^6.5 || ^7.0 || ^8.0 !=8.5.0
Suggests
- neat/http-client: Neat HTTP client components
- neat/http-server: Neat HTTP server components
README
Neat HTTP 组件为您的应用程序提供了一种干净且易于表达的 API,用于访问 HTTP 消息。
要求
要使用 Neat HTTP 组件,您需要
- PHP 7.0 或更高版本
- 一个 PSR-7 HTTP 消息实现
为了发送和接收消息,我们建议使用 neat/http-client 和 neat/http-server 包。
入门指南
要安装此包,只需在命令行中输入 composer
composer require neat/http
读取请求
可以使用如下的简单方法来读取请求。
<?php /** @var Neat\Http\ServerRequest $request */ // Get ?page= query parameter $page = $request->query('page'); // Get posted name field $name = $request->post('name'); // Or just get all posted fields $post = $request->post(); // Who doesn't want a cookie $preference = $request->cookie('preference'); // Get the request method $method = $request->method(); // And of course the requested URL $url = $request->url();
URL 检查
为了节省您手动解析和连接 URL 的麻烦,URL 类将提供帮助。
<?php /** @var Neat\Http\Url $url */ // You can easily print the URL because it converts to a string when needed echo $url; // Or get parts of the url separately $url->scheme(); // 'https' $url->username(); // '' $url->password(); // '' $url->host(); // 'example.com' $url->port(); // null $url->path(); // '/articles' $url->query(); // 'page=2' $url->fragment(); // '' // Do you want to create a slightly different URL based on this one? $mutation = $url->withPath('/just')->withQuery('tweak=any&part=youlike');
文件上传
可以通过请求的 file
方法访问已上传的文件。
<?php /** @var Neat\Http\ServerRequest $request */ // Get uploaded file with the name avatar $file = $request->files('avatar'); // Check the error status if (!$file->ok()) { echo 'Upload error id = ' . $file->error(); } // Get the file name, size and mime type $file->clientName(); // 'selfie.jpg' <-- provided by the client, so consider it unsafe user input $file->clientType(); // 'image/jpeg' <-- provided by the client, so consider it unsafe user input $file->size(); // 21359 // Move the file from its temporary location $file->moveTo('destination/path/including/filename.jpg');