adagio / middleware
该包的最新版本(0.1.0)没有可用的许可证信息。
0.1.0
2017-03-16 17:05 UTC
Requires (Dev)
- phpunit/phpunit: ^6.0
This package is auto-updated.
Last update: 2024-09-17 09:58:59 UTC
README
adagio/middleware
库允许轻松实现具有各种数据类型的中间件。
安装
安装 Composer 并运行以下命令以获取最新版本
composer require adagio/middleware
快速入门
待办事项。
中间件原则
- 中间件签名必须包括输入数据、要填充的输出数据和要调用的下一个中间件。
- 中间件必须返回有效的输出数据。
- 中间件可以在调用下一个中间件之前或之后处理数据。
- 堆栈中的最后一个中间件“隐藏”仅返回输出数据。
过渡到中间件
想象你想要向现有的图像编辑库添加中间件管道。
以下是无需中间件即可完成此操作的方法
// I want to solarize, rotate, unblur and then sepia my image (parameters are // voluntarily omitted for clarity). $image = (new SepiaFilter) ->filter((new UnblurFilter) ->filter((new RotateFilter) ->filter((new SolarizedFilter) ->filter(new Image('/path/to/image')))));
问题是
- 你必须反向声明管道
- 大括号混乱
- 你不能声明以后在其他图像上使用的管道
使用 adagio/middleware
,你可以轻松完成此操作
use Adagio\Middleware\Stack; $pipe = new Stack([ new SolarizedFilter, new RotateFilter, new UnblurFilter, new SepiaFilter, ]); $image = $stack(new Image('/path/to/image'));
过滤器必须遵循以下签名约定
function (Image $image, callable $next): Image { // Maybe do something with $image $resultingImage = $next($image); // Maybe do something with $resultingImage return $resultingImage; }
每个过滤器必须将 $image
传递给管道中的 $next
元素,并在传递之前或之后修改它。
过滤器可以是任何符合给定签名的可调用对象。
更复杂的示例:数据库查询处理
当给定的和返回的对象不同时,中间件更有用。考虑具有以下签名的 SQL 查询处理器
function (SqlQuery $query, ResultSet $resultSet, callable $next): ResultSet
然后你可以提供缓存中间件
final class QueryCache { // ... public function __invoke(SqlQuery $query, ResultSet $resultSet, callable $next): ResultSet { // If the query is already in cache, return the ResultSet and don't // trigger the rest of the middleware stack if ($this->resultSetCache->hasQuery($query)) { return $this->resultSetCache->getFromQuery($query); } $finalResultSet = $next($query, $resultSet); $this->resultSetCache->add($query, $finalResultSet); return $finalResultSet; } }
你也可以提供将 SQL 标准转换为另一种标准的中间件、SQL 验证器、客户端集群/分片解决方案、记录器、性能监控器等中间件。