PHPackages                             tobento/service-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. [Framework](/categories/framework)
4. /
5. tobento/service-middleware

ActiveLibrary[Framework](/categories/framework)

tobento/service-middleware
==========================

A PSR-15 middleware dispatcher with autowiring and alias support.

2.0(7mo ago)02736MITPHPPHP &gt;=8.4

Since Jul 28Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/tobento-ch/service-middleware)[ Packagist](https://packagist.org/packages/tobento/service-middleware)[ Docs](https://www.tobento.ch)[ RSS](/packages/tobento-service-middleware/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (9)Dependencies (10)Versions (11)Used By (6)

Middleware Service
==================

[](#middleware-service)

A PSR-15 middleware dispatcher with autowiring and alias support.

Table of Contents
-----------------

[](#table-of-contents)

- [Getting started](#getting-started)
    - [Requirements](#requirements)
    - [Highlights](#highlights)
- [Documentation](#documentation)
    - [Creating Middleware Dispatcher](#creating-middleware-dispatcher)
    - [Adding Middleware](#adding-middleware)
    - [Aliases](#aliases)
    - [Groups](#groups)
    - [Stack Priority](#stack-priority)
    - [Dispatch](#dispatch)
- [Credits](#credits)

---

Getting started
===============

[](#getting-started)

Add the latest version of the middleware service running this command.

```
composer require tobento/service-middleware

```

Requirements
------------

[](#requirements)

- PHP 8.4 or greater

Highlights
----------

[](#highlights)

- Framework-agnostic, will work with any project
- Decoupled design
- Autowiring middlewares
- Aliasing middlewares

Documentation
=============

[](#documentation)

Creating Middleware Dispatcher
------------------------------

[](#creating-middleware-dispatcher)

```
use Tobento\Service\Middleware\MiddlewareDispatcher;
use Tobento\Service\Middleware\AutowiringMiddlewareFactory;
use Tobento\Service\Middleware\FallbackHandler;
use Tobento\Service\Container\Container;
use Nyholm\Psr7\Factory\Psr17Factory;

// create middleware dispatcher.
$dispatcher = new MiddlewareDispatcher(
    new FallbackHandler((new Psr17Factory())->createResponse(404)),
    new AutowiringMiddlewareFactory(new Container()) // any PSR-11 container
);
```

**new**

You may use the `new` method to create a new instance. It will keep the added aliases though.

```
$newDispatcher = $dispatcher->new();
```

Adding Middleware
-----------------

[](#adding-middleware)

By anonymous function:

```
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

$dispatcher->add(function(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
    return $handler->handle($request);
});
```

By class instance:

```
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;

class Middleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $response = $handler->handle($request);
        $response->getBody()->write('Hello word');
        return $response;
    }
}

$dispatcher->add(new Middleware());
```

By class name:

```
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;

class Middleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $response = $handler->handle($request);
        $response->getBody()->write('Hello word');
        return $response;
    }
}

$dispatcher->add(Middleware::class);
```

By class name with build-in parameters (not resolvable by autowiring):

```
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;

class Middleware implements MiddlewareInterface
{
    public function __construct(
        protected string $name,
    ) {}

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $response = $handler->handle($request);
        $response->getBody()->write('Hello '.$this->name);
        return $response;
    }
}

$dispatcher->add([Middleware::class, 'name' => 'Sam']);
```

Adding multiple at once:

```
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;

class Middleware implements MiddlewareInterface
{
    public function __construct(
        protected string $name,
    ) {}

    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $response = $handler->handle($request);
        $response->getBody()->write('Hello '.$this->name);
        return $response;
    }
}

$dispatcher->add(
    [Middleware::class, 'name' => 'Sam'],
    function(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
        return $handler->handle($request);
    },
);
```

Aliases
-------

[](#aliases)

You might want to use aliases instead of class names:

```
// add single alias.
$dispatcher->addAlias('alias', Middleware::class);

// add multiple alias.
$dispatcher->addAliases([
    'alias' => Middleware::class,
]);

// add middleware by alias.
$dispatcher->add('alias');

// if you have not resolvable parameters:
$dispatcher->add(['alias', 'name' => 'Sam']);
```

Groups
------

[](#groups)

You might want to add a group of middlewares:

```
$dispatcher->addGroup(name: 'api', middlewares: [
    Middleware::class,
    // with build-in parameters:
    [AnotherMiddleware::class, 'name' => 'Sam'],
    // by alias:
    'aliasedMiddleware',
    // by class instance:
    new SomeMiddleware(),
]);

// add middlewares by group:
$dispatcher->add('api');
```

Stack Priority
--------------

[](#stack-priority)

You might want to prioritize the excution order of the middlewares by the following way:

```
// highest number first.
$dispatcher->add(Middleware::class, priority: 100);

$dispatcher->add(AnotherMiddleware::class, priority: 200);
```

Dispatch
--------

[](#dispatch)

```
use Nyholm\Psr7\Factory\Psr17Factory;

$request = (new Psr17Factory())->createServerRequest('GET', 'https://example.com');

$response = $dispatcher->handle($request);
```

Credits
=======

[](#credits)

- [Tobias Strub](https://www.tobento.ch)
- [All Contributors](../../contributors)

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance67

Regular maintenance activity

Popularity15

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity74

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 ~152 days

Recently: every ~119 days

Total

11

Last Release

225d ago

Major Versions

1.x-dev → 2.02025-09-26

PHP version history (2 changes)1.0.0PHP &gt;=8.0

2.0PHP &gt;=8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/055d6a1b5c2384bb179c75ab0b55914231d898fdc4dffeb30770f81200e52206?d=identicon)[TOBENTOch](/maintainers/TOBENTOch)

---

Top Contributors

[![tobento-ch](https://avatars.githubusercontent.com/u/16684832?v=4)](https://github.com/tobento-ch "tobento-ch (19 commits)")

---

Tags

middlewarepackagepsr-15tobento

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[cakephp/authentication

Authentication plugin for CakePHP

1153.6M67](/packages/cakephp-authentication)[neos/flow

Flow Application Framework

862.0M448](/packages/neos-flow)[chubbyphp/chubbyphp-framework

A minimal, highly performant middleware PSR-15 microframework built with as little complexity as possible, aimed primarily at those developers who want to understand all the vendors they use.

13544.4k4](/packages/chubbyphp-chubbyphp-framework)[yiisoft/yii-middleware

Yii Middleware

21151.3k1](/packages/yiisoft-yii-middleware)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)

PHPackages © 2026

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