PSR-15 中间件包的通用工具

v4.0.0 2023-12-17 12:41 UTC

README

Latest Version on Packagist Software License Testing Total Downloads

中间件包使用的通用工具

安装

该包可通过Composer以 middlewares/utils 的方式安装和自动加载。

composer require middlewares/utils

工厂

用于创建PSR-7和PSR-17实例。自动检测 DiactorosGuzzleSlimNyholm/psr7Sunrise,但您可以使用 psr/http-factory 接口注册不同的工厂。

use Middlewares\Utils\Factory;
use Middlewares\Utils\FactoryDiscovery;

// Create PSR-7 instances
$request = Factory::createRequest('GET', '/');
$serverRequest = Factory::createServerRequest('GET', '/');
$response = Factory::createResponse(200);
$stream = Factory::createStream('Hello world');
$uri = Factory::createUri('http://example.com');
$uploadedFile = Factory::createUploadedFile($stream);

// Get PSR-17 instances (factories)
$requestFactory = Factory::getRequestFactory();
$serverRequestFactory = Factory::getServerRequestFactory();
$responseFactory = Factory::getResponseFactory();
$streamFactory = Factory::getStreamFactory();
$uriFactory = Factory::getUriFactory();
$uploadedFileFactory = Factory::getUploadedFileFactory();

// By default, use the FactoryDiscovery class that detects diactoros, guzzle, slim, nyholm and sunrise (in this order of priority),
// but you can change it and add other libraries

Factory::setFactory(new FactoryDiscovery(
    'MyApp\Psr17Factory',
    FactoryDiscovery::SLIM,
    FactoryDiscovery::GUZZLE,
    FactoryDiscovery::DIACTOROS
));

//And also register directly an initialized factory
Factory::getFactory()->setResponseFactory(new FooResponseFactory());

$fooResponse = Factory::createResponse();

分发器

最小化PSR-15兼容分发器。用于测试目的。

use Middlewares\Utils\Dispatcher;

$response = Dispatcher::run([
    new Middleware1(),
    new Middleware2(),
    new Middleware3(),
    function ($request, $next) {
        $response = $next->handle($request);
        return $response->withHeader('X-Foo', 'Bar');
    }
]);

可调用处理程序

用于解析和执行可调用对象。可以作为中间件、服务器请求处理程序或可调用对象使用。

use Middlewares\Utils\CallableHandler;

$callable = new CallableHandler(function () {
    return 'Hello world';
});

$response = $callable();

echo $response->getBody(); //Hello world

HttpErrorException

用于表示HTTP错误的通用异常。

use Middlewares\Utils\HttpErrorException;

try {
    $context = ['problem' => 'Something bad happened'];
    throw HttpErrorException::create(500, $context);
} catch (HttpErrorException $exception) {
    $context = $exception->getContext();
}

有关最近更改的更多信息,请参阅 CHANGELOG,有关贡献详情请参阅 CONTRIBUTING

MIT许可(MIT)。有关更多信息,请参阅 LICENSE