xtompie / middleware
中间件组件
0.1
2021-12-15 19:37 UTC
Requires
- php: >=8.0
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-16 01:36:27 UTC
README
中间件组件
需求
PHP >= 8.0
安装
使用composer
composer require xtompie/middleware
文档
一个中间件是一个可调用的fn(mixed $input, $next): mixed
私有服务中间件
无中间件的服务
<?php use Xtompie\Middleware\Middleware; class TopArticlesService { public function __construct( protected DAO $dao, ) {} public function __invoke(int $limit, int $offset): ArticleCollection { return $this->dao->query([ "select" => "*", "from" => "article", "order" => "top DESC" "offset" => $offset, "limit" => $limit ]) ->mapInto(Article::class) ->pipeInto(ArticleCollection::class); } } }
带有中间件的服务
<?php use Xtompie\Middleware\Middleware; class TopArticlesService { public function __construct( protected DAO $dao, protected InMemoryCacheMiddleware $cache, protected LoggerMiddleware $logger, ) {} public function __invoke(int $limit, int $offset): ArticleCollection { return Middleware::dispatch( [ $this->cache, $this->logger, fn ($args) => return $this->invoke(...$args) ], func_get_args() ) } protected function invoke(int $limit, int $offset): ArticleCollection { return $this->dao->query([ "select" => "*", "from" => "article", "order" => "top DESC" "offset" => $offset, "limit" => $limit ]) ->mapInto(Article::class) ->pipeInto(ArticleCollection::class); } } }
或者带有缓存中间件链
<?php use Xtompie\Middleware\Middleware; class TopArticlesService { public function __construct( protected DAO $dao, protected InMemoryCacheMiddleware $cache, protected LoggerMiddleware $logger, protected Middleware $middleware, ) { $this->middleware = $middleware->withMiddlewares([ $this->cache, $this->logger, fn ($args) => return $this->invoke(...$args) ]) } public function __invoke(int $limit, int $offset): ArticleCollection { return ($this->middleware)(func_get_args()); } protected function invoke(int $limit, int $offset): ArticleCollection { return $this->dao->query([ "select" => "*", "from" => "article", "order" => "top DESC" "offset" => $offset, "limit" => $limit ]) ->mapInto(Article::class) ->pipeInto(ArticleCollection::class); } } }