SlimPHP开发指南五:请求

栏目: 编程语言 · XML · 发布时间: 5年前

内容简介:Your Slim app’s routes and middleware are given a PSR 7 request object that represents the current HTTP request received by your web server. The request object implements the PSR 7 ServerRequestInterface with which you can inspect and manipulate the HTTP r

Your Slim app’s routes and middleware are given a PSR 7 request object that represents the current HTTP request received by your web server. The request object implements the PSR 7 ServerRequestInterface with which you can inspect and manipulate the HTTP request method, headers, and body.

Slim应用程序的路由和中间件被赋予一个PSR 7请求对象,该对象表示web服务器接收到的当前HTTP请求。请求对象实现PSR 7 ServerRequestInterface,您可以使用该接口检查和操作HTTP请求方法、头和主体。

如何获取请求对象

The PSR 7 request object is injected into your Slim application routes as the first argument to the route callback like this:

PSR 7请求对象作为路由回调的第一个参数被注入到slim应用程序路由中,如下所示:

<?php
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

$app = new \Slim\App;
$app->get('/foo', function (ServerRequestInterface $request, ResponseInterface $response) {
    // Use the PSR 7 $request object

    return $response;
});
$app->run();
复制代码
Figure 1: Inject PSR 7 request into application route callback.
复制代码

The Request Method

Every HTTP request has a method that is typically one of:

每个HTTP请求都有一个方法,通常是:

  • GET
  • POST
  • PUT
  • DELETE
  • HEAD
  • PATCH
  • OPTIONS

You can inspect the HTTP request’s method with the Request object method appropriately named getMethod().

您可以使用request对象的getMethod()方法来检查HTTP请求的方法。

$method = $request->getMethod();
复制代码

Because this is a common task, Slim’s built-in PSR 7 implementation also provides these proprietary methods that return true or false.

因为这是一个常见的任务,Slim的内置PSR 7还提供了这些返回true或false的专有方法。

  • $request->isGet()
  • $request->isPost()
  • $request->isPut()
  • $request->isDelete()
  • $request->isHead()
  • $request->isPatch()
  • $request->isOptions()

It is possible to fake or override the HTTP request method. This is useful if, for example, you need to mimic a PUT request using a traditional web browser that only supports GET or POST requests.

可以伪造或覆盖HTTP请求方法。例如,如果您需要使用只支持GET或POST请求的传统web浏览器来模拟PUT请求,这将非常有用。

There are two ways to override the HTTP request method. You can include a _METHOD parameter in a POST request’s body. The HTTP request must use the application/x-www-form-urlencoded content type.

有两种方法覆盖HTTP请求方法。可以在POST请求的主体中包含_METHOD参数。HTTP请求必须使用application/x-www-form-urlencoded内容类型。

POST /path HTTP/1.1
Host: example.com
Content-type: application/x-www-form-urlencoded
Content-length: 22

data=value&_METHOD=PUT
复制代码
Figure 3: Override HTTP method with _METHOD parameter.
复制代码

You can also override the HTTP request method with a custom X-Http-Method-Override HTTP request header. This works with any HTTP request content type.

还可以使用自定义的X-Http-Method-Override HTTP请求头重写HTTP请求方法。这适用于任何HTTP请求内容类型。

POST /path HTTP/1.1
Host: example.com
Content-type: application/json
Content-length: 16
X-Http-Method-Override: PUT

{"data":"value"}
复制代码
Figure 4: Override HTTP method with X-Http-Method-Override header.
复制代码

You can fetch the original (non-overridden) HTTP method with the PSR 7 Request object’s method named getOriginalMethod().

您可以使用PSR 7请求对象的方法getOriginalMethod()获取原始的(未重写的)HTTP方法。

请求URI

Every HTTP request has a URI that identifies the requested application resource. The HTTP request URI has several parts:

每个HTTP请求都有一个URI来标识所请求的应用程序资源。HTTP请求URI有几个部分:

  • Scheme (e.g. http or https)
  • Host (e.g. example.com)
  • Port (e.g. 80 or 443)
  • Path (e.g. /users/1)
  • Query string (e.g. sort=created&dir=asc)

You can fetch the PSR 7 Request object’s URI object with its getUri() method:

您可以使用其getUri()方法获取PSR 7请求对象的URI对象:

$uri = $request->getUri();
复制代码

The PSR 7 Request object’s URI is itself an object that provides the following methods to inspect the HTTP request’s URL parts:

PSR 7请求对象的URI本身就是一个对象,它提供以下方法来检查HTTP请求的URL部分:

  • getScheme()
  • getAuthority()
  • getUserInfo()
  • getHost()
  • getPort()
  • getPath()
  • getBasePath()
  • getQuery() (returns the full query string, e.g. a=1&b=2)
  • getFragment()
  • getBaseUrl()

You can get the query parameters as an associative array on the Request object using getQueryParams().

可以通过请求对象的getQueryParams()方法已关联数组的形式得到查询参数。

You can also get a single query parameter value, with optional default value if the parameter is missing, using getQueryParam( default = null).

您还可以使用getQueryParam($key, $default = null)查询单个参数值,如果缺少该参数,则使用可选的默认值。

Base Path: If your Slim application's front-controller lives in a physical subdirectory beneath your document root directory, you can fetch the HTTP request's physical base path (relative to the document root) with the Uri object's getBasePath() method. This will be an empty string if the Slim application is installed in the document root's top-most directory.

基本路径: 如果Slim应用程序的前端控制器位于文档根目录下的物理子目录中,则可以使用Uri对象的getBasePath()方法获取HTTP请求的物理根路径(相对于文档根目录)。如果Slim应用程序安装在文档根目录的顶部目录中,则该字符串为空。

请求头

Every HTTP request has headers. These are metadata that describe the HTTP request but are not visible in the request’s body. Slim’s PSR 7 Request object provides several methods to inspect its headers.

每个HTTP请求都有头。这些元数据描述HTTP请求,但在请求主体中不可见。Slim的PSR 7请求对象提供了几种方法来检查其头部。

得到所有头

You can fetch all HTTP request headers as an associative array with the PSR 7 Request object’s getHeaders() method. The resultant associative array’s keys are the header names and its values are themselves a numeric array of string values for their respective header name.

您可以使用PSR 7请求对象的getheader()方法以关联数组的形式获取所有HTTP请求头。由此产生的关联数组的键是标题名,其值本身是各自标题名的字符串值的数字数组。

$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
    echo $name . ": " . implode(", ", $values);
}
复制代码
Figure 5: Fetch and iterate all HTTP request headers as an associative array.
复制代码

获得一个头信息

You can get a single header’s value(s) with the PSR 7 Request object’s getHeader($name) method. This returns an array of values for the given header name. Remember, a single HTTP header may have more than one value!

您可以使用PSR 7请求对象的getHeader($name)方法获得单个报头的值。这将返回给定头名的值数组。记住,一个HTTP头可能有多个值!

$headerValueArray = $request->getHeader('Accept');
复制代码
Figure 6: Get values for a specific HTTP header.
复制代码

You may also fetch a comma-separated string with all values for a given header with the PSR 7 Request object’s getHeaderLine( name) method, this method returns a comma-separated string.

您还可以使用PSR 7请求对象的getHeaderLine( name)方法不同,该方法返回一个逗号分隔的字符串。

$headerValueString = $request->getHeaderLine('Accept');
复制代码
Figure 7: Get single header's values as comma-separated string.
复制代码

探测报头

You can test for the presence of a header with the PSR 7 Request object’s hasHeader($name) method.

您可以使用PSR 7请求对象的hasHeader($name)方法测试报头是否存在。

if ($request->hasHeader('Accept')) {
    // Do something
}
复制代码
Figure 8: Detect presence of a specific HTTP request header.
复制代码

请求主体

Every HTTP request has a body. If you are building a Slim application that consumes JSON or XML data, you can use the PSR 7 Request object’s getParsedBody() method to parse the HTTP request body into a native PHP format. Slim can parse JSON, XML, and URL-encoded data out of the box.

每个HTTP请求都有一个主体。如果正在构建一个使用JSON或XML数据的Slim应用程序,可以使用PSR 7请求对象的getParsedBody()方法将HTTP请求体解析为原生 PHP 格式。Slim可以立即解析JSON、XML和url编码的数据。

$parsedBody = $request->getParsedBody();
复制代码
Figure 9: Parse HTTP request body into native PHP format
复制代码
  • JSON requests are converted into associative arrays with json_decode($input, true).

    JSON请求通过json_decode($input, true)转换为关联数组。

  • XML requests are converted into a SimpleXMLElement with simplexml_load_string($input).

    XML请求通过simplexml_load_string($input)转换为SimpleXMLElement。

  • URL-encoded requests are converted into a PHP array with parse_str($input).

    url编码的请求被转换成一个带有parse_str($input)的PHP数组。

For URL-encoded requests, you can also get a single parameter value, with optional default value if the parameter is missing, using getParsedBodyParam( default = null).

对于url编码的请求,还可以使用getParsedBodyParam( default = null)获得单个参数值,如果缺少参数,则使用可选的默认值。

Technically speaking, Slim’s PSR 7 Request object represents the HTTP request body as an instance of \Psr\Http\Message\StreamInterface. You can get the HTTP request body StreamInterface instance with the PSR 7 Request object’s getBody() method. The getBody() method is preferable if the incoming HTTP request size is unknown or too large for available memory.

从技术上讲,Slim的PSR 7请求对象将HTTP请求体表示为\ PSR \ HTTP \Message\StreamInterface的一个实例。您可以使用PSR 7请求对象的getBody()方法获得HTTP请求体流接口实例。如果传入的HTTP请求大小未知或对于可用内存过大,则使用getBody()方法更好。

$body = $request->getBody();
复制代码
Figure 10: Get HTTP request body
复制代码

The resultant \Psr\Http\Message\StreamInterface instance provides the following methods to read and iterate its underlying PHP resource.

生成的\Psr\Http\Message\StreamInterface实例提供了以下方法来读取和迭代它的底层PHP资源。

  • getSize()
  • tell()
  • eof()
  • isSeekable()
  • seek()
  • rewind()
  • isWritable()
  • write($string)
  • isReadable()
  • read($length)
  • getContents()
  • getMetadata($key = null)

重新解析body

When calling getParsedBody on the Request object multiple times, the body is only parsed once, even if the Request body is modified in the meantime. To ensure the body is reparsed, the Request object’s method reparseBody can be used.

当对请求对象多次调用getParsedBody时,即使同时修改了请求主体,也只解析一次主体。为了确保主体被重新解析,可以使用请求对象的reparseBody方法。

上传文件

The file uploads in $_FILES are available from the Request object’s getUploadedFiles() method. This returns an array keyed by the name of the element.

$_FILES中的文件上载可以从请求对象的getUploadedFiles()方法获得。这将返回一个数组,其键值为 元素的名称。

$files = $request->getUploadedFiles();
复制代码
Figure 11: Get uploaded files
复制代码

Each object in the $files array is a instance of \Psr\Http\Message\UploadedFileInterface and supports the following methods:

$files数组中的每个对象都是\Psr\Http\Message\UploadedFileInterface的一个实例,并且支持以下方法:

  • getStream()
  • moveTo($targetPath)
  • getSize()
  • getError()
  • getClientFilename()
  • getClientMediaType()

See thecookbook on how to upload files using a POST form.

Request Helpers

Slim’s PSR 7 Request implementation provides these additional proprietary methods to help you further inspect the HTTP request.

Slim的PSR 7请求实现提供了这些额外的专有方法来帮助您进一步检查HTTP请求。

检测XHR请求

You can detect XHR requests with the Request object’s isXhr() method. This method detects the presence of the X-Requested-With HTTP request header and ensures its value is XMLHttpRequest.

您可以使用请求对象的isXhr()方法检测XHR请求。此方法检测X-Request-With HTTP请求头的存在,并确保其值为XMLHttpRequest。

POST /path HTTP/1.1
Host: example.com
Content-type: application/x-www-form-urlencoded
Content-length: 7
X-Requested-With: XMLHttpRequest

foo=bar
复制代码
Figure 13: Example XHR request.
复制代码
if ($request->isXhr()) {
    // Do something
}
复制代码

Content Type

You can fetch the HTTP request content type with the Request object’s getContentType() method. This returns the Content-Type header’s full value as provided by the HTTP client.

您可以使用请求对象的getContentType()方法获取HTTP请求内容类型。这将返回HTTP客户机提供的Content-Type头的完整值。

$contentType = $request->getContentType();
复制代码

Media Type

You may not want the complete Content-Type header. What if, instead, you only want the media type? You can fetch the HTTP request media type with the Request object’s getMediaType() method.

您可能不需要完整的内容类型头。如果您只需要媒体类型呢?您可以使用请求对象的getMediaType()方法获取HTTP请求媒体类型。

$mediaType = $request->getMediaType();
复制代码

You can fetch the appended media type parameters as an associative array with the Request object’s getMediaTypeParams() method.

您可以使用请求对象的getMediaTypeParams()方法以关联数组的形式获取附加的媒体类型参数。

$mediaParams = $request->getMediaTypeParams();
复制代码

Character Set

One of the most common media type parameters is the HTTP request character set. The Request object provides a dedicated method to retrieve this media type parameter.

最常见的媒体类型参数之一是HTTP请求字符集。请求对象提供了一个专门的方法来检索该媒体类型参数。

$charset = $request->getContentCharset();
复制代码

Content Length

You can fetch the HTTP request content length with the Request object’s getContentLength() method.

您可以使用请求对象的getContentLength()方法获取HTTP请求内容长度。

$length = $request->getContentLength();
复制代码

Request Parameter

To fetch single request parameter value, use methods: getParam(), getQueryParam(), getParsedBodyParam(), getCookieParam(), getServerParam(), counterparts of PSR-7’s plural form get*Params() methods.

要获取单个请求参数值,可以使用以下方法:getParam()、getQueryParam()、getParsedBodyParam()、getCookieParam()、getServerParam(),以及与PSR-7复数形式get*Params()方法对应的方法。

For example, to get a single Server Parameter:

$foo = $request->getServerParam('HTTP_NOT_EXIST', 'default_value_here');
复制代码

Route Object

Sometimes in middleware you require the parameter of your route.

有时在中间件中需要路由的参数。

In this example we are checking first that the user is logged in and second that the user has permissions to view the particular video they are attempting to view.

在本例中,我们首先检查用户是否已登录,然后检查用户是否具有查看其试图查看的特定视频的权限。

$app->get('/course/{id}', Video::class.":watch")->add(Permission::class)->add(Auth::class);

    //.. In the Permission Class's Invoke
    /** @var $route \Slim\Route */
    $route = $request->getAttribute('route');
    $courseId = $route->getArgument('id');
复制代码

Media Type Parsers

Slim looks as the request’s media type and if it recognises it, will parse it into structured data available via $request->getParsedBody(). This is usually an array, but is an object for XML media types.

如果Slim识别出了媒体类型,就会将它解析为可通过$request->getParsedBody()获得的结构化数据。这通常是一个数组,但它是XML媒体类型的对象。

The following media types are recognised and parsed:

  • application/x-www-form-urlencoded
  • application/json
  • application/xml & text/xml

If you want Slim to parse content from a different media type then you need to either parse the raw body yourself or register a new media parser. Media parsers are simply callables that accept an $input string and return a parsed object or array.

如果希望Slim解析来自不同媒体类型的内容,则需要自己解析原始体或注册新媒体解析器。媒体解析器只是接受$input字符串并返回已解析对象或数组的可调用项。

Register a new media parser in an application or route middleware. Note that you must register the parser before you try to access the parsed body for the first time.

在应用程序或路由中间件中注册新媒体解析器。注意,在第一次尝试访问被解析的主体之前,必须注册解析器。

For example, to automatically parse JSON that is sent with a text/javascript content type, you register a media type parser in middleware like this:

例如,要自动解析文本/javascript内容类型发送的JSON,您需要在中间件中注册一个媒体类型解析器,如下所示:

// Add the middleware
$app->add(function ($request, $response, $next) {
    // add media parser
    $request->registerMediaTypeParser(
        "text/javascript",
        function ($input) {
            return json_decode($input, true);
        }
    );

    return $next($request, $response);
});
复制代码

Attributes

With PSR-7 it is possible to inject objects/values into the request object for further processing. In your applications middleware often need to pass along information to your route closure and the way to do is it is to add it to the request object via an attribute.

使用PSR-7,可以将对象/值注入请求对象以进行进一步处理。在应用程序中,中间件通常需要将信息传递给路由闭包,方法是通过属性将其添加到请求对象中。

Example, Setting a value on your request object.

$app->add(function ($request, $response, $next) {
    $request = $request->withAttribute('session', $_SESSION); //add the session storage to your request as [READ-ONLY]
    return $next($request, $response);
});
复制代码

Example, how to retrieve the value.

$app->get('/test', function ($request, $response, $args) {
    $session = $request->getAttribute('session'); //get the session from the request

    return $response->write('Yay, ' . $session['name']);
});
复制代码

The request object also has bulk functions as well. $request->getAttributes() and $request->withAttributes()

请求对象还具有批量函数。$request->getAttributes()和$request->withAttributes()


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Mission Python

Mission Python

Sean McManus / No Starch Press / 2018-9-18 / GBP 24.99

Launch into coding with Mission Python, a space-themed guide to building a complete computer game in Python. You'll learn programming fundamentals like loops, strings, and lists as you build Escape!, ......一起来看看 《Mission Python》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具