1 Star 2 Fork 0

inhere / php-middleware

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

Middleware

The psr-15 HTTP Middleware implement.

ref PSR 15

项目地址

安装

  • composer 命令
composer require inhere/middleware
  • composer.json
{
    "require": {
        "inhere/middleware": "dev-master"
    }
}
  • 直接拉取
git clone https://github.com/inhere/php-middleware.git // github
git clone https://gitee.com/inhere/php-middleware.git // git@osc

使用

基本使用

function func_middleware($request, RequestHandlerInterface $handler)
{
    echo ">>> 0 before\n";
    $res = $handler->handle($request);
    echo "0 after >>>\n";

    return $res;
}

function func_middleware1($request, RequestHandlerInterface $handler)
{
    echo ">>> n before \n";
    $res = $handler->handle($request);
    echo "n after >>>\n";

    return $res;
}

$chain = new MiddlewareStack([
    'func_middleware',
    function (ServerRequestInterface $request, RequestHandlerInterface $handler) {
        echo ">>> 1 before \n";
        $res = $handler->handle($request);
        $res->getBody()->write(' + node 1');
        echo "1 after >>> \n";
        return $res;
    },
    function (ServerRequestInterface $request, RequestHandlerInterface $handler) {
        echo ">>> 2 before \n";
        $res = $handler->handle($request);
        $res->getBody()->write(' + node 2');
        echo "2 after >>> \n";
        return $res;
    },
    function (ServerRequestInterface $request, RequestHandlerInterface $handler) {
        echo ">>> 3 before \n";
        $res = $handler->handle($request);
        $res->getBody()->write(' + node 3');
        echo "3 after >>> \n";
        return $res;
    },
    function (ServerRequestInterface $request, RequestHandlerInterface $handler) {
//        $res = HttpFactory::createResponse();
//        $res->getBody()->write('content');

        echo ">>> 4 before \n";
        $res = $handler->handle($request);
        $res->getBody()->write('node 4');
        echo "4 after >>> \n";

        return $res;
    },
    'func_middleware1'
]);

$request = HttpFactory::createServerRequest('GET', 'http://www.abc.com/home');

$chain->setCoreHandler(function (ServerRequestInterface $request) {
    echo " (this is core)\n";

    return HttpFactory::createResponse()->write('-CORE-');
});

$res = $chain($request);

echo PHP_EOL . 'response content: ', (string)$res->getBody() . PHP_EOL;

运行 php examples/test.php

$ php examples/test.php
>>> 0 before
>>> 1 before
>>> 2 before
>>> 3 before
>>> 4 before
>>> n before
 (this is core)
n after >>>
4 after >>>
3 after >>>
2 after >>>
1 after >>>
0 after >>>

response content: node 4 + node 3 + node 2 + node 1

一个基于中间件的应用示例

引入相关类

路由器,psr 7的http message 库

use Inhere\Http\HttpFactory;
use Inhere\Http\HttpUtil;
use Inhere\Middleware\MiddlewareStackAwareTrait;
use Inhere\Route\Base\RouterInterface;
use Inhere\Route\ORouter;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

创建一个应用类


$app = new class implements RequestHandlerInterface {
    use MiddlewareStackAwareTrait;

    /**
     * @var ORouter
     */
    private $router;

    public function run(ServerRequestInterface $request)
    {
        $response = $this->callStack($request);

        Http::respond($response);
    }

    /**
     * 在这里处理请求返回响应对象
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     * @throws Throwable
     */
    public function handleRequest(ServerRequestInterface $request): ResponseInterface
    {
        $method = $request->getMethod();
        $uriPath = $request->getUri()->getPath();
        $response = HttpFactory::createResponse();

        try {
            // $this->router->match($uriPath, $method);
            $result = $this->router->dispatch(null, $uriPath, $method);
            $response->getBody()->write($result);
        } catch (Throwable $e) {
            $response->getBody()->write($e->getTraceAsString());
        }

        return $response;
    }

    /**
     * @return RouterInterface
     */
    public function getRouter(): RouterInterface
    {
        return $this->router;
    }

    /**
     * @param RouterInterface $router
     */
    public function setRouter(RouterInterface $router)
    {
        $this->router = $router;
    }
};

创建路由器并注册路由

$router = new ORouter();

/**
 * add routes
 */
$router->get('/', function () {
   echo 'hello, world';
});

$router->get('/hello/{name}', function ($args) {
    echo "hello, {$args['name']}";
});

添加中间件

/**
 * add middleware
 */
$app->use(function (ServerRequestInterface $request, RequestHandlerInterface $handler) {
    echo 'before handle0 > ';
    $res = $handler->handle($request);
    echo ' > after handle0';

    return $res;
});

$app->use(function (ServerRequestInterface $request, RequestHandlerInterface $handler) {
    echo 'before handle1 > ';
    $res = $handler->handle($request);
    echo ' > after handle1';

    return $res;
});

准备运行

/**
 * run
 */
$req = HttpFactory::createServerRequestFromArray($_SERVER);

$app->setRouter($router);
$app->run($req);

运行dev server

$ php -S 127.0.0.1:8009 examples/app.php

访问: http://127.0.0.1:8009

visit: /hello/tom response:

before handle0 > before handle1 > hello, tom > after handle1 > after handle0

ref project

License

MIT

The MIT License (MIT) Copyright (c) 2016 inhere Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

the psr-15 HTTP Middlewares implement. PSR-15中间件调用实现 展开 收起
PHP
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
PHP
1
https://gitee.com/inhere/php-middleware.git
git@gitee.com:inhere/php-middleware.git
inhere
php-middleware
php-middleware
master

搜索帮助