PHPackages                             lighthouse/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. lighthouse/middleware

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

lighthouse/middleware
=====================

PSR-15 HTTP Middleware Pipeline for the Lighthouse framework

v0.1.0(8mo ago)0111MITPHPPHP ^8.2CI failing

Since Dec 17Pushed 8mo agoCompare

[ Source](https://github.com/RichardTrujilloTorres/middleware)[ Packagist](https://packagist.org/packages/lighthouse/middleware)[ RSS](/packages/lighthouse-middleware/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (7)Versions (2)Used By (1)

Lighthouse Middleware
=====================

[](#lighthouse-middleware)

A PSR-15 HTTP Middleware Pipeline for the Lighthouse framework.

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

[](#installation)

```
composer require lighthouse/middleware
```

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

[](#requirements)

- PHP 8.2 or higher

Features
--------

[](#features)

- PSR-15 compliant middleware pipeline
- Onion-style middleware processing
- Callable middleware support
- Request/response modification
- Short-circuit capability

Quick Start
-----------

[](#quick-start)

### Basic Pipeline

[](#basic-pipeline)

```
use Lighthouse\Middleware\Pipeline;
use Lighthouse\Middleware\CallableMiddleware;
use Psr\Http\Server\RequestHandlerInterface;

$pipeline = new Pipeline();

// Add middleware
$pipeline->pipe(new LoggingMiddleware());
$pipeline->pipe(new AuthenticationMiddleware());
$pipeline->pipe(new RoutingMiddleware());

// Process request
$response = $pipeline->handle($request);
```

### Callable Middleware

[](#callable-middleware)

You can use closures instead of full middleware classes:

```
$pipeline->pipe(function ($request, $handler) {
    // Before: modify request
    $request = $request->withAttribute('start_time', microtime(true));

    // Call next middleware
    $response = $handler->handle($request);

    // After: modify response
    return $response->withHeader('X-Request-Time', microtime(true) - $request->getAttribute('start_time'));
});
```

### Middleware Order (Onion Model)

[](#middleware-order-onion-model)

Middleware is processed in order added, but responses flow back in reverse:

```
$pipeline->pipe($middleware1);  // Executes first, returns last
$pipeline->pipe($middleware2);  // Executes second, returns second-to-last
$pipeline->pipe($middleware3);  // Executes last, returns first

// Request flow:  middleware1 → middleware2 → middleware3 → handler
// Response flow: middleware1 ← middleware2 ← middleware3 ← handler
```

### Short-Circuiting

[](#short-circuiting)

Middleware can return early without calling the next handler:

```
$pipeline->pipe(function ($request, $handler) {
    if (!$this->isAuthenticated($request)) {
        // Return immediately, skip remaining middleware
        return new Response(401);
    }

    return $handler->handle($request);
});
```

### Fallback Handler

[](#fallback-handler)

Set a handler to use when no middleware generates a response:

```
use Lighthouse\Middleware\FallbackHandler;

// Throw exception (default)
$pipeline = new Pipeline();

// Return 404 response
$pipeline = new Pipeline(new FallbackHandler(
    fn() => new Response(404, body: 'Not Found')
));

// Or set later
$pipeline->fallback($customHandler);
```

### Add Multiple Middleware

[](#add-multiple-middleware)

```
$pipeline->through([
    new CorsMiddleware(),
    new AuthMiddleware(),
    new RateLimitMiddleware(),
]);
```

Creating Middleware
-------------------

[](#creating-middleware)

Implement `MiddlewareInterface`:

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

class TimingMiddleware implements MiddlewareInterface
{
    public function process(
        ServerRequestInterface $request,
        RequestHandlerInterface $handler
    ): ResponseInterface {
        $start = microtime(true);

        $response = $handler->handle($request);

        $duration = microtime(true) - $start;

        return $response->withHeader('X-Response-Time', sprintf('%.3fms', $duration * 1000));
    }
}
```

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

[](#api-reference)

### Pipeline

[](#pipeline)

MethodDescription`pipe(MiddlewareInterface|callable $middleware)`Add middleware to pipeline`through(array $middleware)`Add multiple middleware`fallback(RequestHandlerInterface $handler)`Set fallback handler`handle(ServerRequestInterface $request)`Process request through pipeline`getMiddleware()`Get middleware stack`clear()`Remove all middleware### CallableMiddleware

[](#callablemiddleware)

Wraps a callable as `MiddlewareInterface`:

```
$middleware = new CallableMiddleware(
    fn($request, $handler) => $handler->handle($request)
);
```

### NextHandler

[](#nexthandler)

Wraps a callable as `RequestHandlerInterface`:

```
$handler = new NextHandler(
    fn($request) => new Response(200)
);
```

### FallbackHandler

[](#fallbackhandler)

Default handler when middleware stack is exhausted:

```
// Throws RuntimeException
$handler = new FallbackHandler();

// Returns custom response
$handler = new FallbackHandler(fn() => new Response(404));
```

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Part of the Lighthouse Framework
--------------------------------

[](#part-of-the-lighthouse-framework)

This package is part of the [Lighthouse Framework](https://github.com/lighthouse-php), an educational PHP framework designed to teach how modern frameworks work internally.

###  Health Score

30

—

LowBetter than 61% of packages

Maintenance62

Regular maintenance activity

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

243d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13813941?v=4)[Richard Trujillo](/maintainers/richardtrujillotorres)[@RichardTrujilloTorres](https://github.com/RichardTrujilloTorres)

---

Top Contributors

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

---

Tags

httpmiddlewarepsr-15dispatcherpipelinelighthouse

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.9k20.0M1.9k](/packages/cakephp-cakephp)[sunrise/http-router

A powerful solution as the foundation of your project.

16852.3k12](/packages/sunrise-http-router)[cakephp/authentication

Authentication plugin for CakePHP

1214.3M118](/packages/cakephp-authentication)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[mezzio/mezzio

PSR-15 Middleware Microframework

3973.9M133](/packages/mezzio-mezzio)[typo3/cms-adminpanel

TYPO3 CMS Admin Panel - The Admin Panel displays information about your site in the frontend and contains a range of metrics including debug and caching information.

115.8M71](/packages/typo3-cms-adminpanel)

PHPackages © 2026

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