PHPackages                             enjoys/middleware-dispatcher - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. enjoys/middleware-dispatcher

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

enjoys/middleware-dispatcher
============================

1.0.2(11mo ago)054MITPHPPHP ^8.1

Since Sep 4Pushed 11mo agoCompare

[ Source](https://github.com/Enjoyzz/middleware-dispatcher)[ Packagist](https://packagist.org/packages/enjoys/middleware-dispatcher)[ RSS](/packages/enjoys-middleware-dispatcher/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (6)Versions (4)Used By (0)

HTTP Middleware Dispatcher
==========================

[](#http-middleware-dispatcher)

A PSR-15 compliant middleware dispatcher that provides flexible middleware queue management with support for various middleware formats.

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

[](#requirements)

- PHP 8.1 or higher
- PSR-15 implementation
- PSR-7/PSR-17 implementations for HTTP messages

Installation
------------

[](#installation)

```
composer require enjoys/middleware-dispatcher
```

Usage
-----

[](#usage)

Basic Usage
-----------

[](#basic-usage)

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

// Create your final request handler
$finalHandler = new class implements RequestHandlerInterface {
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        // Return your final response
        return new Response();
    }
};

// Create the dispatcher
$dispatcher = new HttpMiddlewareDispatcher($finalHandler);

// Set up middleware queue
$middlewares = [
    new MyFirstMiddleware(),
    new MySecondMiddleware(),
    function ($request, $handler) {
        // Callable middleware
        return $handler->handle($request);
    }
];

$dispatcher->setQueue($middlewares);

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

### With Middleware Resolver

[](#with-middleware-resolver)

```
use Enjoys\MiddlewareDispatcher\MiddlewareResolverInterface;
use Psr\Http\Server\MiddlewareInterface;

class MyMiddlewareResolver implements MiddlewareResolverInterface
{
    public function resolve(mixed $entry): ?MiddlewareInterface
    {
        if (is_string($entry) && class_exists($entry)) {
            return new $entry();
        }

        if (is_array($entry) && count($entry) === 2) {
            return new ClassMethodMiddleware($entry[0], $entry[1]);
        }

        return $entry;
    }
}

$resolver = new MyMiddlewareResolver();
$dispatcher = new HttpMiddlewareDispatcher($finalHandler, $resolver);
```

### Example PSR-11 Container Middleware Resolver

[](#example-psr-11-container-middleware-resolver)

```
use Enjoys\MiddlewareDispatcher\MiddlewareResolverInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Server\MiddlewareInterface;

final class Psr11ContainerMiddlewareResolver implements MiddlewareResolverInterface
{
    public function __construct(private readonly ContainerInterface $container)
    {
    }

    public function resolve(mixed $entry): null|MiddlewareInterface|callable
    {
        if ($entry instanceof MiddlewareInterface || is_callable($entry)) {
            return $entry;
        }

        if (is_string($entry)) {
            try {
                $entry = $this->container->get($entry);
                if ($entry instanceof MiddlewareInterface) {
                    return $entry;
                }
            } catch (ContainerExceptionInterface) {
                return null;
            }
        }
        return null;
    }
}
```

### Adding Middleware Dynamically

[](#adding-middleware-dynamically)

```
// Add middleware to the current position in the queue
$dispatcher->addQueue([
    new AdditionalMiddleware(),
    function ($request, $handler) {
        // Another callable middleware
        return $handler->handle($request);
    }
]);
```

API Reference
-------------

[](#api-reference)

### Constructor

[](#constructor)

```
public function __construct(
    RequestHandlerInterface $requestHandler,
    ?MiddlewareResolverInterface $resolver = null
)
```

### Methods

[](#methods)

`setQueue(ArrayIterator|array $queue): void`Sets the middleware queue. Throws InvalidArgumentException if queue is empty.

`handle(ServerRequestInterface $request): ResponseInterface`Processes the request through the middleware queue.

`addQueue(array $middlewares): void`Adds middleware(s) at the current position in the queue.

### Middleware Formats

[](#middleware-formats)

The dispatcher supports multiple middleware formats:

**MiddlewareInterface instances**: Objects implementing Psr\\Http\\Server\\MiddlewareInterface

**Callables**: Functions or closures with signature function(ServerRequestInterface, RequestHandlerInterface): ResponseInterface

**Resolvable entries**: Any format that can be resolved by your MiddlewareResolverInterface

### Error Handling

[](#error-handling)

- Throws `InvalidArgumentException` when setting an empty queue
- Throws `RuntimeException` when encountering invalid middleware entries

###  Health Score

30

—

LowBetter than 61% of packages

Maintenance51

Moderate activity, may be stable

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

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

Total

3

Last Release

346d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/25447823?v=4)[enjoys](/maintainers/enjoys)[@enjoys](https://github.com/enjoys)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[mcp/sdk

Model Context Protocol SDK for Client and Server applications in PHP

1.6k2.2M144](/packages/mcp-sdk)[jaxon-php/jaxon-core

Jaxon is an open source PHP library for easily creating Ajax web applications

73151.3k35](/packages/jaxon-php-jaxon-core)[flarum/core

Delightfully simple forum software.

211.5M2.5k](/packages/flarum-core)[xima/xima-typo3-frontend-edit

Frontend Edit - This extension provides an edit button for editors within frontend content elements.

1615.6k](/packages/xima-xima-typo3-frontend-edit)[eliashaeussler/typo3-solver

Solver - Extends TYPO3's exception handling with AI generated solutions. Problems can also be solved from command line. Several OpenAI parameters are configurable and prompts and solution providers can be customized as desired.

302.1k](/packages/eliashaeussler-typo3-solver)

PHPackages © 2026

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