webiny/http

Webiny Http 组件

v1.6.1 2017-09-29 08:12 UTC

README

Http 组件包括 RequestResponseCookieSession 类。

安装组件

安装组件的最佳方式是使用 Composer。

composer require webiny/http

要获取该包的附加版本,请访问 Packagist 页面

使用方法

访问这些类的首选方式是使用 HttpTrait

    class MyClass{
        use \Webiny\Component\Http\HttpTrait;

        function myFunction(){
            // access `Request` instance
            $this->httpRequest();

            // access `Cookie` instance
            $this->httpCookie();

            // access `Session` instance
            $this->httpSession();

            // create new `Response` instance
            $this->httpResponse('output content');
             
            // redirect
            $this->httpRedirect('http://youtube.com/');
        }
    }

要注册配置与组件,只需调用 Http::setConfig($pathToYamlConfig)

Request

Request 类提供了不同的辅助方法,如

  • getCurrentUrl - 返回当前 URL
  • getClientIp - 返回当前客户端的 IP 地址
  • isRequestSecured - 检查请求是否在 'https' 协议之后

以及许多其他方法。 注意: 所有函数都会检查转发响应头,并验证它们是否在定义的受信任代理列表中。

除了提供辅助函数外,Request 类还提供了用于操作全局变量(如 $_SERVER$_GET$_POST$_FILES)的包装器。

服务器

Server 类是所有(已记录的)$_SERVER 属性的包装器,基于 php.net 官方文档中的列表。 https://php.ac.cn/manual/en/reserved.variables.server.php

以下是一个示例用法

class MyClass{
        use \Webiny\Component\Http\HttpTrait;

        function myFunction(){
           // get request method
            $this->httpRequest()->server()->requestMethod(); // "GET"
        }
    }

注意: Server 方法 不会 检查反向代理的转发响应头。它们只是 $_SERVER 属性的客观包装器。请使用 Request 类中的方法来获取客户端 IP、主机名等属性,这些属性会验证受信任代理。

$_GET$_POST

要访问 $_GET 属性,请使用 query 方法,要访问 $_POST,请使用 post 方法。两种方法都接受两个参数。第一个参数是属性的键,第二个是在键不存在时返回的默认值。

以下是一个示例用法

class MyClass{
        use \Webiny\Component\Http\HttpTrait;

        function myFunction(){
            // get 'name' param from current query string
            $this->httpRequest()->query('name');

            // get 'color' param from $_POST, and if color is not defined, return 'blue'
            $this->httpRequest()->post('color', 'blue');
        }
    }

有效载荷

要访问 Payload 属性,请使用 payload 方法。 Payload 会自动读取 php://input 并对输出进行 json_decode

访问有效载荷值

class MyClass{
        use \Webiny\Component\Http\HttpTrait;

        function myFunction(){
            // get 'name' from payload
            $this->httpRequest()->payload('name');
        }
    }

$_FILES

$_FILES 包装器提供了处理上传文件的一种更好的方式。这个过程分为两个步骤。在第一步中,您使用 Request 类上的 files 方法获取文件。之后,您可以将文件移动到所需的位置。

class MyClass{
        use \Webiny\Component\Http\HttpTrait;

        function myFunction(){
            // get the uploaded file
            $file = $this->httpRequest()->files('avatar');

            // move it to desired destination
            $file->store('/var/tmp');
        }
    }

Session

Webiny 框架为您提供了两个内置的会话存储处理程序,即原生处理程序和缓存处理程序。原生处理程序使用内置的 PHP 会话处理程序,而缓存处理程序使用提供的缓存驱动程序。使用缓存处理程序,您可以轻松地在多个服务器之间共享会话并提高性能。当前支持的缓存驱动程序是 Cache 组件支持的所有驱动程序。

会话缓存处理程序配置

默认定义的存储处理程序是原生处理程序。如果您想使用缓存处理程序,您必须首先设置一个缓存驱动程序(阅读 Cache 组件的 README 文件),然后将缓存驱动程序链接到会话处理程序,如下所示

    Http:
        Session:
            Storage:
                Driver: '\Webiny\Component\Http\Session\Storage\CacheStorage'
                Params:
                    Cache: 'TestCache'
                Prefix: 'wfs_'
                ExpireTime: 86400

有两个最重要的属性您需要更改,即 DriverParams.CacheDriver 属性必须指向 \Webiny\Component\Http\Session\Storage\CacheStorage,而 Params.Cache 必须包含已注册的 Cache 服务的名称。您的代码中无需进行其他更改,您可以使用 Session 类来处理会话。

自定义会话存储处理程序

您可以通过创建一个实现 \Webiny\Component\Http\Session\SessionStorageInterface 的类来实现自己的会话存储处理程序。创建此类后,只需将 Driver 参数指向您的类,并通过 Params 配置属性可选地传递请求的构造函数参数。

会话操作

操作会话相当简单,只需访问当前会话处理程序,然后提供必要的会话方法,如 getsavegetSessionId

以下是一个示例

class MyClass{
        use \Webiny\Component\Http\HttpTrait;

        function myFunction(){
            // save into session
            $this->httpSession()->save('my_key', 'some value');

            // read from session
            $this->httpSession()->get('my_key');
        }
    }

Cookie

操作 cookie 与操作会话类似,您有一个 cookie 存储处理程序,它提供了存储和访问 cookie 值的必要方法。默认情况下,只有一个本地内置的存储处理程序。

Cookie 配置

cookie 配置包括定义默认存储驱动程序和一些可选参数,如 PrefixHttpOnlyExpireTime

    Http:
        Cookie:
            Storage:
                Driver: '\Webiny\Component\Http\Cookie\Storage\NativeStorage'
            Prefix: 'wfc_'
            HttpOnly: 'true'
            ExpireTime: 86400

自定义 cookie 存储处理程序

要实现自定义 cookie 存储处理程序,您首先需要创建一个实现 \Webiny\Component\Http\Cookie\CookieStorageHandler 接口的存储处理程序类。创建成功后,您现在必须更改 cookie 配置中的 Storage.Driver 参数,以便指向您的类。

操作 cookies

为了读取和存储 cookies,您必须获取当前 cookie 存储驱动程序的实例,它为您提供了必要的方法。Cookie 类提供了这种访问方式。

class MyClass{
        use \Webiny\Component\Http\HttpTrait;

        function myFunction(){
            // save cookie
            $this->httpCookie()->save('my_cookie', 'some value');

            // read cookie
            $this->httpCookie()->get('my_key');
        }
    }

Response

Response 类提供构建并发送输出到浏览器的功能。该类本身无需任何配置。

要创建 Response 实例,您可以使用 HttpTrait、类构造函数或 Response::create 静态方法。

    // using the trait
    class MyClass{
        use \Webiny\Component\Http\HttpTrait;

        function myFunction(){
            // create and sent the output
            $this->httpResponse('Hello World!')->send();
        }
    }

    // using constructor
    $response = new Response('Hello World!');
    $response->send();

    // using static method
    $response = Response::create('Hello World!');
    $response->send();

方法

Response 类提供了一些有用的方法

  • setContent:设置输出内容
  • setStatusCode:设置 HTTP 状态码
  • setContentType:设置内容类型头(默认为:"text/html")
  • setContentType:设置内容字符集(默认为:"UTF-8")
  • setHeader:设置或添加响应头

缓存控制

提供了一个缓存控制类,用于控制响应对象上的缓存控制头。要访问缓存控制选项,请在 Response 对象上使用 cacheControl 方法。

    $response = new Response('Hello World!');
    $cacheControl = $response->cacheControl();

CacheControl 默认调用 setAsDontCache 方法,该方法设置缓存控制头,使浏览器不缓存响应。要覆盖它,您可以通过提供包含您自己的缓存控制头信息数组的选项,或者只需调用 setAsCache 方法,该方法设置响应缓存头,以便输出可以被浏览器缓存。

JsonResponse

此类通过设置默认内容类型为 "application/json" 来扩展 Response 类。该类可以通过构造函数或静态简写方法访问。

    // using constructor
    $jsonResponse = new Response\JsonResponse($someArrayOrObject);
    $jsonResponse->send(); // send output to browser

    // short-hand
    Response\JsonResponse::sendJson($someArrayOrObject)); // output is automatically sent

资源

要运行单元测试,您需要使用以下命令

$ cd path/to/Webiny/Component/Http/
$ composer.phar install
$ phpunit