PHPackages                             inhere/middleware - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. inhere/middleware

ActiveLibrary[HTTP &amp; Networking](/categories/http)

inhere/middleware
=================

the psr-15, psr-7 middleware library of the php

v1.0.4(7y ago)478MITPHPPHP &gt;7.1.0

Since Feb 28Pushed 7y ago1 watchersCompare

[ Source](https://github.com/inhere/php-middleware)[ Packagist](https://packagist.org/packages/inhere/middleware)[ Docs](https://github.com/inhere/php-middleware)[ RSS](/packages/inhere-middleware/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (1)Dependencies (2)Versions (6)Used By (0)

Middleware
==========

[](#middleware)

The psr-15 HTTP Middleware implement.

ref [PSR 15](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-15-request-handlers.md)

项目地址
----

[](#项目地址)

- **github**
- **git@osc**

安装
--

[](#安装)

- 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;
    },
    '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
>>> n before
 (THIS IS CORE)
n after >>>
3 after >>>
2 after >>>
1 after >>>
0 after >>>

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

```

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

[](#一个基于中间件的应用示例)

### 引入相关类

[](#引入相关类)

路由器，psr 7的http message 库

```
use PhpComp\Http\Message\HttpFactory;
use PhpComp\Http\Message\HttpUtil;
use Inhere\Middleware\MiddlewareStackAwareTrait;
use Inhere\Route\RouterInterface;
use Inhere\Route\Router;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
```

### 创建一个应用类

[](#创建一个应用类)

```
$app = new class implements RequestHandlerInterface {
    use MiddlewareStackAwareTrait;

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

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

        HttpUtil::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 Inhere\Route\Router();

/**
 * 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

[](#运行dev-server)

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

访问：

visit: `/hello/tom`response:

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

```

ref project
-----------

[](#ref-project)

-
-
-

License
-------

[](#license)

MIT

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~75 days

Total

5

Last Release

2697d ago

PHP version history (2 changes)v1.0.0PHP &gt;7.0.0

v1.0.4PHP &gt;7.1.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/d23e1decaf354e8f36a7ad61128865dc78dd63336c2d023d79aa3ff8ba2a05ff?d=identicon)[inhere](/maintainers/inhere)

---

Top Contributors

[![inhere](https://avatars.githubusercontent.com/u/5302062?v=4)](https://github.com/inhere "inhere (23 commits)")

---

Tags

middlewaremiddleware-pipelinepsr-15psr-7middlewarelibrarypsr-15Middleware Dispatcher

### Embed Badge

![Health badge](/badges/inhere-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/inhere-middleware/health.svg)](https://phpackages.com/packages/inhere-middleware)
```

###  Alternatives

[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M97](/packages/mezzio-mezzio)[relay/relay

A PSR-15 server request handler.

3302.1M86](/packages/relay-relay)[php-middleware/php-debug-bar

PHP Debug Bar PSR-15 middleware with PSR-7

76433.5k2](/packages/php-middleware-php-debug-bar)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)[jimtools/jwt-auth

PSR-15 JWT Authentication middleware, A replacement for tuupola/slim-jwt-auth

20142.3k3](/packages/jimtools-jwt-auth)[oscarotero/middleland

PSR-15 middleware dispatcher

3781.0k6](/packages/oscarotero-middleland)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
