rnr1721/le7-middleware

Le7 框架或其他 PHP 项目的 PSR-15 中间件实现

1.0.8 2023-05-20 17:08 UTC

This package is auto-updated.

Last update: 2024-09-20 20:00:49 UTC


README

PSR-15 中间件实现,适用于 le7 MVC PHP 框架或任何 PHP 项目

它能做什么?

这是 PSR-15 接口的标准实现。您可以在此处了解更多信息:https://www.php-fig.org/psr/psr-15/

如何使用它?

use Core\RequestHandler\MiddlewareDispatcherGeneric;

        // $responseFactory is implementation of ResponseFactoryInterface
        $response = $responseFactory->createResponse(404);
        $defaultRequestHandler = new DefaultHandler($response);
        $middlewares = new MiddlewareDispatcherDefault($defaultRequestHandler);

        // Middlewares are implementation of MiddlewareInterface
        $middleware1 = new Middleware1();
        $middleware2 = new Middleware2();
        $middleware3 = new Middleware3();
        $middleware4 = new Middleware4();

        // If need to run in reverse order
        $middleware->setReverse(true);

        // Add middlewares. It will be run in reverse order (if turn on):
        // Default Handler at first, and 4,3,2,1 after
        $middlewares->add($middleware1);
        $middlewares->add($middleware2);
        $middlewares->add($middleware3);
        $middlewares->add($middleware4);

        // Get response after process middlewares
        // $request is PSR Request
        $response = $middlewares->handle($request);

干净的中间件示例

<?php

declare(strict_types=1);

namespace Middleware;

use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class TestMiddleware implements MiddlewareInterface
{

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        return $response;
    }

}

使用示例

<?php

declare(strict_types=1);

namespace Middleware;

use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class TestMiddleware implements MiddlewareInterface
{

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        return $response->withStatus(201);
    }

}
<?php

declare(strict_types=1);

namespace Middleware;

use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class TestMiddleware implements MiddlewareInterface
{

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        
        // do something

        // To next handler
        return $handler->handle($request);
    }

}