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(8mo ago)04MITPHPPHP ^8.1

Since Sep 4Pushed 8mo 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 1mo 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

31

—

LowBetter than 68% of packages

Maintenance60

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

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

254d 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.4k423.9k30](/packages/mcp-sdk)[psr7-sessions/storageless

Storageless PSR-7 Session support

652373.0k8](/packages/psr7-sessions-storageless)[markstory/asset_compress

An asset compression plugin for CakePHP. Provides file concatenation and a flexible filter system for preprocessing and minification.

3761.0M11](/packages/markstory-asset-compress)[jaxon-php/jaxon-core

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

73142.3k25](/packages/jaxon-php-jaxon-core)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)[tomasnorre/crawler

Crawler extension for TYPO3

58397.5k1](/packages/tomasnorre-crawler)

PHPackages © 2026

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