bittyphp/http

此包已被弃用且不再维护。未建议替代包。

PSR-7 和 PSR-17 HTTP 实现。

维护者

详细信息

github.com/bittyphp/http

此包尚未发布版本,且信息不多。


README

Build Status Codacy Badge PHPStan Enabled Mutation Score Total Downloads License

完整的 PSR-7 HTTP 和 PSR-17 HTTP 工厂实现。

安装

最好使用 Composer 安装。

$ composer require bittyphp/http

概要

抽象消息

所有 RequestResponse 类共享一个基类 AbstractMessage,它提供了与消息头部和正文交互的方法。

可用方法

以下方法在所有 RequestResponse 对象中可用

getProtocolVersion()

获取 HTTP 协议版本作为字符串(例如,"1.0" 或 "1.1")。

withProtocolVersion($version)

返回一个具有给定 HTTP 协议版本字符串(例如,"1.0" 或 "1.1")的新消息实例。

getHeaders()

返回与消息相关联的头部数组。数组键是头部名称,每个值是该头部的字符串数组。

hasHeader($name)

对给定的头部名称进行不区分大小写的比较,以查看它是否存在于消息的头部中。如果找到,返回 true,如果没有找到,返回 false

getHeader($name)

返回给定不区分大小写头部值的字符串数组。如果头部不存在,则返回空数组。

getHeaderLine($name)

返回给定不区分大小写头部所有值的逗号分隔字符串。如果头部不存在,则返回空字符串。

withHeader($name, $value)

返回一个新的消息实例,同时用指定的值或值替换给定的头部。

<?php

use Bitty\Http\ServerRequest;

$request = new ServerRequest(...);

$newRequest = $request->withHeader(
    'Content-Type',
    'text/html'
);

$newRequest = $request->withHeader(
    'Accept',
    ['application/json', 'application/xml']
);

withAddedHeader($name, $value)

返回一个新的消息实例,同时添加给定的头部和指定的值或值。与 withHeader() 非常相似,但会保留所有现有头部。

withoutHeader($name)

返回一个新的消息实例,同时完全删除给定的头部。

getBody()

Psr\Http\Message\StreamInterface 格式获取消息体。

withBody($body)

返回一个新的消息实例,使用指定的消息体。消息体必须是 Psr\Http\Message\StreamInterface 的一个实例。

请求

有两种类型的请求:RequestServerRequestRequest 类用于出站请求,例如,您向另一台服务器发送请求。ServerRequest 类用于入站请求,例如,有人向您的网站发起请求,由您处理并响应。

除非您正在构建 HTTP 客户端,否则您最有可能只使用 ServerRequest。两者都包含在内,因为该库是一个完整的 PSR-7 实现。

Request

Request 类用于构建出站的客户端请求。请求被认为是不可变的;所有改变请求状态的方法都会返回一个新的实例,该实例包含更改,原始请求始终保持不变。

构建 Request

RequestFactory 是构建请求最一致的方式,无论使用的框架是什么。所有 PSR-17 实现共享此方法签名。

<?php

use Bitty\Http\RequestFactory;
use Psr\Http\Message\RequestInterface;

$factory = new RequestFactory();

/** @var RequestInterface */
$request = $factory->createRequest('GET', '/some/path?foo=bar');

或者,您可以手动构建请求。

<?php

use Bitty\Http\Request;

$method = 'GET';
$uri = 'http://example.com/';
$headers = ['Content-Type' => 'application/json'];
$body = '{"ping": "pong"}';
$protocolVersion = '1.1';

// All of the parameters are optional.
$request = new Request(
    $method,
    $uri,
    $headers,
    $body,
    $protocolVersion
);

可用方法

除了从 AbstractMessage 继承的所有方法外,还提供了以下方法

getRequestTarget()

获取客户端看到的消息请求目标。在大多数情况下,这将是指定的 URI 的原点形式,除非提供了特定值。例如,如果您请求 "http://example.com/search?q=test",则这将包含 "/search?q=test")。

withRequestTarget($requestTarget)

返回一个新的实例,其消息请求目标为所提供的内容。

getMethod()

获取请求的 HTTP 方法。

withMethod($method)

返回一个新的实例,将消息的 HTTP 方法设置为所给内容。方法名称应该是大写,但它不会为您纠正大小写。

getUri()

获取请求的 URI,作为一个 Psr\Http\Message\UriInterface

withUri($uri, $preserveHost = false)

返回一个新的实例,将消息的 URI 设置为所给内容。它必须提供 Psr\Http\Message\UriInterface。如果 preserve host 设置为 true,则不会更改请求的域名,除非已经设置了域名。

ServerRequest

ServerRequest 类继承自 Request,用于构建一个服务器端入站请求。请求被视为不可变;所有改变请求状态的方法都会返回一个新的实例,该实例包含更改,而原始请求保持不变。

构建 ServerRequest

ServerRequestFactory 是构建请求最一致的方法,无论使用的框架是什么。所有 PSR-17 实现都共享这个方法签名。

<?php

use Bitty\Http\ServerRequestFactory;
use Psr\Http\Message\ServerRequestInterface;

$factory = new ServerRequestFactory();

/** @var ServerRequestInterface */
$request = $factory->createServerRequest('GET', '/some/path?foo=bar');
$request = $factory->createServerRequest('GET', '/some/path?foo=bar', $serverParams);

可用方法

除了从 Request 继承的所有方法外,以下方法也可用

getServerParams()

获取请求的服务器参数。通常这是 $_SERVER 变量的内容,但不一定如此。

withServerParams($params)

返回一个新的请求实例,其中包含更新的服务器参数。

getCookieParams()

获取请求的 Cookie 参数。返回的结构与 $_COOKIE 提供的格式相同。

withCookieParams($cookies)

返回一个新的请求实例,其中包含更新的 Cookie 参数。参数 $cookies 必须与 $_COOKIE 提供的结构相匹配。

getQueryParams()

获取请求的查询字符串参数。通常这是 $_GET 变量的内容,但不一定如此。查询参数也可能与 URI 查询参数不同步,因为设置一个不会自动设置另一个。

withQueryParams($query)

返回一个新的请求实例,其中包含更新的查询参数。更新查询参数不会自动更新请求的 URI。

getUploadedFiles()

获取一个规范化文件上传的数组,其中每个数组节点都是一个 Psr\Http\Message\UploadedFileInterface

withUploadedFiles($uploadedFiles)

返回一个新的请求实例,其中包含指定的文件树。数组中的每个节点都必须是一个 Psr\Http\Message\UploadedFileInterface

<?php

use Bitty\Http\ServerRequest;

$request = new ServerRequest(...);

// A simple list.
$newRequest = $request->withUploadedFiles(
    [
        'fileA' => $fileA,
        'fileB' => $fileB,
    ]
);

// A nested list.
$newRequest = $request->withUploadedFiles(
    [
        'images' => [
            'small' => $fileA,
            'large' => $fileB,
        ],
        'foo' => [
            'bar' => [
                'baz' => $fileC,
            ],
        ],
    ]
);
getParsedBody()

获取请求主体的参数。如果请求的 Content-Type 是 application/x-www-form-urlencodedmultipart/form-data,并且请求方法是 POST,则此方法将返回一个类似于 $_POST 的数组。对于其他方法,如 PUTPATCH,只有在 Content-Type 是 application/x-www-form-urlencodedapplication/json 时,它才会解析主体,并返回结果数组。

withParsedBody($body)

返回一个新的请求实例,其中包含指定的解析后的主体。它只接受 arrayobjectnull 值。

getAttributes()

获取与请求关联的所有自定义属性。属性是添加到请求中的应用特定数据,可以是任何东西,例如路由数据或身份验证标志。

getAttribute($name, $default = null)

获取请求中的给定属性。如果未设置属性,将返回默认值。

withAttribute($name, $value)

返回一个新的请求实例,其中包含指定的属性。

<?php

use Bitty\Http\ServerRequest;

$request = new ServerRequest(...);

// If you have a route such as /product/{id}
// And a request for /product/123
// You can set the 'id' attribute to the product ID
$newRequest = $request->withAttribute('id', 123);

// Some controller for the route
$controller = function ($request) {
    // Look up product data
    $productId = $request->getAttribute('id');
    $product = $someRepository->find($productId);

    // Do something with $product
};

$controller($newRequest);
withoutAttribute($name)

返回一个新的请求实例,其中不包含指定的属性。

响应

有三个响应类可用,主要是为了方便,但它们都扩展了 Response

Response

Response 类用于向客户端返回数据,通常是 HTML 的形式。

构建 Response

ResponseFactory 是构建响应的最一致的方式,无论使用的框架是什么。所有 PSR-17 实现都共享此方法签名。

<?php

use Bitty\Http\ResponseFactory;
use Psr\Http\Message\ResponseInterface;

$factory = new ResponseFactory();

/** @var ResponseInterface */
$response = $factory->createResponse();
$response = $factory->createResponse(404);
$response = $factory->createResponse(404, 'Not Found');

或者您可以手动构建一个。

<?php

use Bitty\Http\Response;

// Defaults to a 200 OK response.
$response = new Response('Hello, world!');

// Use a given status code.
$response = new Response('', 204);

// Send custom headers.
$response = new Response(
    'Goodbye, world!',
    302,
    ['Location' => '/bye-bye']
);

可用方法

除了从 AbstractMessage 继承的所有方法外,还提供了以下方法

getStatusCode()

可用于获取响应的 HTTP 状态码(例如,200404)。

getReasonPhrase()

可用于获取状态码的相关文本(例如,OKNot Found)。

withStatus()

允许您设置状态和(可选)状态码的理由短语,并返回一个新响应对象中的更改。

<?php

use Bitty\Http\Response;

$response = new Response(...);

$newResponse = $response->withStatus(204);
$newResponse = $response->withStatus(204, 'No Content');

JsonResponse

JsonResponseResponse 类的一个便利扩展,用于简化返回 JSON 数据。它自动将给定的任何数据编码为 JSON,并将 Content-Type 标头设置为 application/json

<?php

use Bitty\Http\JsonResponse;

// Defaults to a 200 OK response.
$response = new JsonResponse(['message' => 'Hello, world!']);

// Custom 404 response.
$response = new JsonResponse(
    ['error' => 'Page not found'],
    404
);

// Include additional headers.
$response = new JsonResponse(
    ['error' => 'Invalid credentials'],
    401,
    ['X-Auth' => 'Failed']
);

RedirectResponse

RedirectResponseResponse 类的一个便利扩展,用于简化重定向。它自动设置 Location 标头,并在正文中包含一个指向要重定向到的 URI 的链接。

<?php

use Bitty\Http\RedirectResponse;

// Defaults to a 302 redirect.
$redirect = new RedirectResponse('/some/path');

// Use a given status code.
$redirect = new RedirectResponse('/some/path', 301);

// Send custom headers.
$redirect = new RedirectResponse(
    '/some/path',
    302,
    ['X-Message' => 'Bye-bye']
);

文件上传

UploadedFile 类试图解决 PHP 结构 $_FILES 全局时的问题。

构建 UploadedFile

UploadedFileFactory 是构建 UploadedFile 的最一致的方式,无论使用的框架是什么。所有 PSR-17 实现都共享此方法签名。

<?php

use Bitty\Http\UploadedFileFactory;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;

$factory = new UploadedFileFactory();

/** @var StreamInterface */
$stream = ...;

/** @var UploadedFileInterface */
$file = $factory->createUploadedFile($stream);
$file = $factory->createUploadedFile($stream, $size, $error, $clientFilename, $clientMediaType);

可用方法

以下方法可用

getStream()

获取表示文件上传的 Psr\Http\Message\StreamInterface

moveTo($targetPath)

将文件移动到目标路径。内部使用 move_uploaded_file()rename(),具体取决于是否在 SAPI 或非 SAPI 环境中调用。

getSize()

获取文件大小。

getError()

获取与文件关联的错误代码。这将返回 UPLOAD_ERR_* 常量 之一。

getClientFilename()

获取客户端发送的文件名。此值的真实性不可信,因为它很容易被伪造。

getClientMediaType()

获取客户端发送的媒体类型。此值的真实性不可信,因为它很容易被伪造。

流提供了一种标准化的方式来访问可流式传输的数据,例如请求/响应体和文件上传。然而,它可能在代码的任何其他部分都很有用。

构建 Stream

StreamFactory 是构建 Stream 最一致的方式,无论使用的框架是什么。所有 PSR-17 实现都共享此方法签名。

<?php

use Bitty\Http\StreamFactory;
use Psr\Http\Message\StreamInterface;

$factory = new StreamFactory();

/** @var StreamInterface */
$stream = $factory->createStream('string of data');
$stream = $factory->createStreamFromFile('/path/to/file', 'r');
$stream = $factory->createStreamFromResource($resource);

或者,您可以手动构建一个 Stream

<?php

use Bitty\Http\Stream;

$stream = new Stream('string of data');
$stream = new Stream($resource);

可用方法

以下方法可用

close()

关闭流及其任何底层资源。

detach()

将底层资源从流中分离并返回它。

getSize()

获取流的尺寸,如果已知。

tell()

返回文件指针的当前位置。

eof()

如果流位于流的末尾,则返回 true。

isSeekable()

返回流是否可寻址。

seek($offset, $whence = SEEK_SET)

在流中定位到指定位置。 $whence 应该是 PHP 的 SEEK_* 常量 之一。

rewind()

将流定位到开始位置。

isWritable()

返回流是否可写。

write($string)

将数据写入流。

isReadable()

返回流是否可读。

read($length)

从流中读取数据。

getContents()

返回流的剩余内容。

getMetadata($key = null)

获取流元数据作为关联数组或检索特定键。返回的键与PHP的stream_get_meta_data()函数返回的键相同。

URIs

Uri类使得处理URI值更加容易,因为你可以轻松地获取或设置URI的特定部分。

构建一个Uri

UriFactory是构建Uri的最一致方式,无论使用哪种框架。所有PSR-17实现都共享此方法签名。

<?php

use Bitty\Http\UriFactory;
use Psr\Http\Message\UriInterface;

$factory = new UriFactory();

/** @var UriInterface */
$uri = $factory->createUri('/some/path?foo=bar');
$uri = $factory->createUri('https://example.com/search?q=test');

或者,您可以手动构建一个Uri

<?php

use Bitty\Http\Uri;

$uri = new Uri('/some/path?foo=bar');
$uri = new Uri('https://example.com/search?q=test');

可用方法

以下方法可用

getScheme()

检索URI的方案组件。

getAuthority()

检索URI的授权组件。URI的授权语法为[user-info@]host[:port]

getUserInfo()

检索URI的用户信息组件。语法为username[:password]

getHost()

检索URI的主机组件。

getPort()

检索URI的端口组件。如果端口是标准端口(例如,HTTP的80或HTTPS的443),则返回null

getPath()

检索URI的路径组件。

getQuery()

检索URI的查询字符串。

getFragment()

检索URI的片段组件。

withScheme($scheme)

返回具有指定方案的新实例。

withUserInfo($user, $password = null)

返回具有指定用户信息的新实例。

withHost($host)

返回具有指定主机的新实例。

withPort($port)

返回具有指定端口的新实例。

withPath($path)

返回具有指定路径的新实例。

withQuery($query)

返回具有指定查询的新实例。

withFragment($片段)

返回一个新的实例,该实例具有指定的片段。