PHPackages                             coroq/request-handler - 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. coroq/request-handler

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

coroq/request-handler
=====================

A base class for PSR-15 request handlers that reduces the boilerplate

v1.0.0(yesterday)01↑2900%MITPHPPHP ^8.0

Since Jul 30Pushed yesterdayCompare

[ Source](https://github.com/coroq-com/request-handler)[ Packagist](https://packagist.org/packages/coroq/request-handler)[ RSS](/packages/coroq-request-handler/feed)WikiDiscussions main Synced today

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

coroq/request-handler
=====================

[](#coroqrequest-handler)

A base class for PSR-15 request handlers that reduces the boilerplate.

The same handler, first in plain PSR-15, then with this library:

Plain PSR-15
------------

[](#plain-psr-15)

```
class ContactController implements RequestHandlerInterface {
  public function __construct(
    private ResponseFactoryInterface $responseFactory,
  ) {
  }

  public function handle(ServerRequestInterface $request): ResponseInterface {
    return match ($request->getMethod()) {
      'GET' => $this->showForm($request),
      'POST' => $this->submit($request),
      default => $this->responseFactory->createResponse(405),
    };
  }

  private function showForm(ServerRequestInterface $request): ResponseInterface {
    $error = $request->getQueryParams()['error'] ?? null;
    // ... render the form ...
  }

  private function submit(ServerRequestInterface $request): ResponseInterface {
    $body = $request->getParsedBody();
    $message = is_array($body) ? ($body['message'] ?? '') : '';
    // ... store it, redirect ...
  }
}
```

With coroq/request-handler
--------------------------

[](#with-coroqrequest-handler)

```
use Coroq\RequestHandler\RequestHandler;

class ContactController extends RequestHandler {
  public function __construct(
    private ResponseFactoryInterface $responseFactory,
  ) {
  }

  public function handleGet(): ResponseInterface {
    $error = $this->get['error'] ?? null;
    // ... render the form ...
  }

  public function handlePost(): ResponseInterface {
    $message = $this->post['message'] ?? '';
    // ... store it, redirect ...
  }
}
```

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

[](#installation)

```
composer require coroq/request-handler
```

Requires PHP ^8.0. Depends only on `psr/http-message` and `psr/http-server-handler`.

How it works
------------

[](#how-it-works)

`RequestHandler` implements PSR-15 `RequestHandlerInterface`. `handle()` does two things:

- loads the request into properties (`$request`, `$get`, `$post`, etc.),
- dispatches by HTTP method to `handleGet()`, `handlePost()`, etc.

Handler methods
---------------

[](#handler-methods)

MethodHTTP method`handleGet()`GET`handlePost()`POST`handlePut()`PUT`handleDelete()`DELETE`handlePatch()`PATCH`handleQuery()`QUERY (the draft "safe method with a body")`handleHead()`HEAD`handleOptions()`OPTIONS`handleOthers()`any other methodOverride the ones your handler supports. Every default implementation throws `MethodNotAllowedException` — except `handleHead()`, which falls back to `handleGet()` (see below). `handle()` itself is deliberately overridable — for method-agnostic handlers, or to wrap the dispatch with `parent::handle()`.

Request properties
------------------

[](#request-properties)

The request and its contents are easily accessible from every handler method:

PropertyContent`$this->request`the `ServerRequestInterface` itself`$this->get`query parameters (like `$_GET`)`$this->post`body parameters (like `$_POST`)`$this->cookie`cookies (like `$_COOKIE`)`$this->attributes`request attributes (path parameters etc.)Two notes:

- `$this->post` is filled only when the parsed body is an array (HTML forms). For JSON, parse the body into an array in an earlier middleware, or read `$this->request->getBody()` yourself.
- Request handlers hold the request, so use one instance per request. Don't share instances via a caching container.

Handling HEAD requests
----------------------

[](#handling-head-requests)

`handleHead()` falls back to `handleGet()` by default, so a handler that supports GET answers HEAD automatically. A HEAD response is the GET response without its body — stripping the body is the job of your emitter or web server. Override `handleHead()` when you want to answer HEAD yourself.

Handling unsupported methods and OPTIONS
----------------------------------------

[](#handling-unsupported-methods-and-options)

The base never builds a response; when a method is not supported it throws. `MethodNotAllowedException` carries `allowedMethods` — the methods the handler supports, detected from which `handleXxx()` are overridden. Catch it once, in a middleware near the front of your queue:

```
use Coroq\RequestHandler\MethodNotAllowedException;

try {
  return $handler->handle($request);
}
catch (MethodNotAllowedException $exception) {
  // include OPTIONS because this middleware answers it
  $allow = join(', ', array_unique([...$exception->allowedMethods, 'OPTIONS']));
  if ($request->getMethod() === 'OPTIONS') {
    return $this->responseFactory->createResponse(204)->withHeader('Allow', $allow);
  }
  return $this->responseFactory->createResponse(405)->withHeader('Allow', $allow);
}
```

This one catch gives every handler an RFC 9110 compliant 405 and a generic OPTIONS answer (CORS preflights included).

RequestLoadingTrait on its own
------------------------------

[](#requestloadingtrait-on-its-own)

The request loading is available standalone:

```
use Coroq\RequestHandler\RequestLoadingTrait;

abstract class MyBase implements RequestHandlerInterface {
  use RequestLoadingTrait;

  public function handle(ServerRequestInterface $request): ResponseInterface {
    $this->loadRequest($request);
    // $this->get, $this->post, ... are now ready
  }
}
```

License
-------

[](#license)

MIT

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance100

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

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

1d ago

### Community

Maintainers

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

---

Top Contributors

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

---

Tags

httppsr-7psr-15controllerrequest-handler

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/coroq-request-handler/health.svg)

```
[![Health](https://phpackages.com/badges/coroq-request-handler/health.svg)](https://phpackages.com/packages/coroq-request-handler)
```

###  Alternatives

[guzzlehttp/psr7

PSR-7 message implementation that also provides common utility methods

7.9k1.1B4.1k](/packages/guzzlehttp-psr7)[sunrise/http-router

A powerful solution as the foundation of your project.

17451.8k11](/packages/sunrise-http-router)[mezzio/mezzio

PSR-15 Middleware Microframework

3923.8M127](/packages/mezzio-mezzio)[psr/http-server-middleware

Common interface for HTTP server-side middleware

185103.9M2.0k](/packages/psr-http-server-middleware)[laminas/laminas-stratigility

PSR-7 middleware foundation for building and dispatching middleware pipelines

587.2M104](/packages/laminas-laminas-stratigility)[middlewares/request-handler

Middleware to execute request handlers

451.8M30](/packages/middlewares-request-handler)

PHPackages © 2026

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