ellipse/handlers-container

Psr-15 请求处理代理 Psr-11 容器条目

1.0.3 2018-03-19 15:50 UTC

This package is auto-updated.

Last update: 2024-08-26 00:11:41 UTC


README

此包提供了一种Psr-15请求处理代理,该代理代理Psr-11容器条目。

需求 php >= 7.0

安装 composer require ellipse/handlers-container

运行测试 ./vendor/bin/kahlan

使用容器条目作为请求处理器

Ellipse\Handlers\ContainerRequestHandler 类接受 Psr\Container\ContainerInterface 的实现和一个容器 ID 作为参数。其 ->handle() 方法使用此 ID 从容器中检索请求处理器,并代理其 ->handle() 方法。

当容器条目需要在处理请求时解析时,这可能很有用。

当从容器检索的值不是实现 Psr\Http\Server\RequestHandlerInterface 的对象时,会抛出 Ellipse\Handlers\Exceptions\ContainedRequestHandlerTypeException

<?php

namespace App;

use SomePsr11Container;

use Ellipse\Handlers\ContainerRequestHandler;

// Get some Psr-11 container.
$container = new SomePsr11Container;

// Add a request handler in the container.
$container->set('some.request.handler', function () {

    return new SomeRequestHandler;

});

// Create a container request handler with the Psr-11 container and the entry id.
$handler = new ContainerRequestHandler($container, 'some.request.handler');

// The handler ->handle() method retrieve the request handler from the container and proxy it.
$response = $handler->handle($request);

使用自动装配的示例

在容器中注册每个请求处理器类可能会很麻烦。以下是如何使用来自ellipse/container-reflection 包的 Ellipse\Container\ReflectionContainer 类自动装配请求处理器实例的方法。

<?php

namespace App;

use Psr\Http\Server\RequestHandlerInterface;

use SomePsr11Container;

use Ellipse\Container\ReflectionContainer;
use Ellipse\Handlers\ContainerRequestHandler;

// Get some Psr-11 container.
$container = new SomePsr11Container;

// Decorate the container with a reflection container.
// Specify the request handler implementations can be auto wired.
$reflection = new ReflectionContainer($container, [
    RequestHandlerInterface::class,
]);

// Create a container request handler with the reflection container and a request handler class name.
$handler = new ContainerRequestHandler($reflection, SomeRequestHandler::class);

// An instance of SomeRequestHandler is built and its ->handle() method is proxied.
$response = $handler->handle($request);