neat/http

Neat HTTP 组件

0.6.3 2020-01-14 08:04 UTC

README

Stable Version Build Status

Neat HTTP 组件为您的应用程序提供了一种干净且易于表达的 API,用于访问 HTTP 消息。

要求

要使用 Neat HTTP 组件,您需要

为了发送和接收消息,我们建议使用 neat/http-clientneat/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');