krak/mw-compose

中间件组合工具

v0.1.0 2016-08-31 19:16 UTC

This package is not auto-updated.

Last update: 2024-09-20 22:48:23 UTC


README

Mw Compose 是一个简单的工具库,用于组合/创建中间件。算法被通用地编写,因此这个中间件系统可以用于任何类型的应用程序。

创建中间件的主要函数是 Krak\Mw\composeMwSet

一个 中间件 是任何接受两个参数的 php 可调用函数:参数和集合中的下一个中间件。

参数 可以是您应用程序中任何特定内容。在 krak/mw http 框架中,参数是 Psr\Http\Message\ServerRequestInterface,但您的应用程序可以将其设为数组、元组、对象、标量等。

API

// composes a middleware set into a single executable middleware executed in LIFO order
// So, the *last* middleware in the set will be the *first* to execute
callable Krak\Mw\mwComposeSet(array $mws, $last = null);

何时使用中间件

中间件实现了装饰器模式,同时更加优雅。通常,如果您想使用装饰器,但想以任意顺序轻松添加装饰器,那么使用中间件模式是最佳选择。如果需要装饰很多服务,使用装饰器定义服务可能很繁琐;使用中间件,您只需创建您的中间件服务,然后组合它们,无需担心用最后装饰的服务构建每个服务。

示例

以下是中间件模式的一个简单示例

<?php

function mw1() {
    return function($param, $next) {
        return $next($param < 5 ? 5 : $param);
    };
}
function mw2() {
    return function($param, $next) {
        return $param + 5;
    };
}

// LIFO execution
$mw = Krak\Mw\composeMwSet([
    mw2(),
    mw1()
]);

assert($mw(0) == 10);

如您所见,第一个中间件只是“装饰”了参数,然后将其传递给下一个处理器,然后处理器实际返回了响应。

装饰示例

<?php

function decorated1($handler) {
    return function($param) use ($handler) {
        return $handler($param < 5 ? 5 : $param);
    };
}

function decorated2() {
    return function($param) {
        return $param + 5;
    };
}

$handler = decorated2();
$handler = decorated1($handler);
assert($handler(0) == 10);

如您所见,如果有任何装饰器需要额外的依赖项或您有更多的装饰器,那么创建最终的装饰处理器的过程可能很繁琐。