hypercharge / php-middleware
PHP 通用中间件实现。
dev-master
2014-01-27 18:10 UTC
Requires
- php: >=5.3
Requires (Dev)
- phpunit/phpunit: ~3.7.0
This package is not auto-updated.
Last update: 2024-09-23 14:23:38 UTC
README
这是一个用于在 PHP 项目中使用中间件模式的通用库。
php-middleware
是 ruby middleware 库的 PHP 版本。
目前只实现了 ruby middleware
的一部分功能。请继续关注,以了解更多功能的迁移。
要开始使用,最佳参考是 用户指南。
安装
本项目以 composer 包的形式分发。
在项目根目录下创建一个 composer.json
文件
{ "require": { "hypercharge/php-middleware": "dev-master" } }
在终端中 cd
到项目根目录并运行命令
$ php composer.phar install
基本示例
以下是一个使用此库的基本示例。如果您不了解中间件是什么,请阅读 ruby 中间件文档。此示例仅旨在快速展示库的外观。
<?php // basic env instance class class LogEnv { public $log = array(); public function to_string() { return join($this->log, "\n"); } } // Basic middleware that just logs the inbound and // outbound steps to env class Trace implements Middleware\Middleware { private $app; private $value; public function __construct($app, $value) { $this->app = $app; $this->value = $value; } public function call($env) { $env->log[] = '--> '.$this->value; $this->app->call($env); $env->log[] = '<-- '.$this->value; } } // the env object passed to each middleware call($env) method $env = new LogEnv(); // build the actual middleware stack which runs a sequence // of slightly different versions of our middleware $stack = new Middleware\Builder(); $stack ->uses('Trace', 'A') ->uses('Trace', 'B') ->uses('Trace', 'C'); // run it $stack->call($env); echo $env->to_string();
输出结果
--> A
--> B
--> C
<-- C
<-- B
<-- A
运行测试
$ ./vendor/bin/phpunit