• Stars
    star
    45
  • Rank 624,037 (Top 13 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PSR-15 middleware to execute request handlers

middlewares/request-handler

Latest Version on Packagist Software License Testing Total Downloads

Middleware to execute request handlers discovered by a router.

Requirements

Installation

This package is installable and autoloadable via Composer as middlewares/request-handler.

composer require middlewares/request-handler

You may also want to install any route middleware like middlewares/fast-route or middlewares/aura-router for routing.

Purpose

There are two completely separate steps when it comes to route handling:

  1. Determining if the request is valid and can be resolved by the application.
  2. Handling the request inside the application.

The first step usually resolves into a route callback, while the product of the second one is usually the result of executing that callback.

Multiple things that can happen between the first and second steps: input validation, authentication, authorization, etc. and in some scenarios we may not want to continue processing the request (e.g. auth, accessing DB resources, etc.) if that would ultimately fail to resolve e.g. procuding an HTTP 400 error.

Splitting routing from request handling allows us to use any middleware between these two steps. It also makes the request-handler middleware able to be used with any routing component.

Example

A routing middleware needs to be called before the request can be handled. In this example, we will use fast-route middleware.

// Create the routing dispatcher
$fastRouteDispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
    $r->get('/hello/{name}', HelloWorldController::class);
});

$dispatcher = new Dispatcher([
    new Middlewares\FastRoute($fastRouteDispatcher),
    // ...
    new Middlewares\RequestHandler(),
]);

$response = $dispatcher->dispatch(new ServerRequest('/hello/world'));

When the request handler is invoked, it expects a request attribute to be defined that contains a reference to the handler. The handler must be a string, a callable or an object implementing MiddlewareInterface or RequestHandlerInterface. If it's a string, a ContainerInterface will be used to resolve it and get the MiddlewareInterface or RequestHandlerInterface to use. If it's a callable, it will be converted automatically to MiddlewareInterface using the Middlewares\Utils\CallableHandler

// Use a PSR-11 container to create the intances of the request handlers
$container = new RequestHandlerContainer();

$dispatcher = new Dispatcher([
    // ...
    new Middlewares\RequestHandler($container),
]);

Usage

Define the container used to resolve the handlers if they are provided as string (or an array with 2 strings). By default will use Middlewares\Utils\RequestHandlerContainer.

// Use the default PSR-11 container to create the intances of the request handlers
$handler = new Middlewares\RequestHandler();

// Use a custom PSR-11 container
$container = new RequestHandlerContainer();

$handler = new Middlewares\RequestHandler($container);

handlerAttribute

Configures the attribute name used to get the handler reference in the server request. The default is request-handler.

Dispatcher::run([
    (new Middlewares\RequestHandler())->handlerAttribute('route'),
]);

continueOnEmpty

If the server request attribute is empty or does not exists, an exception is throwed. This function changes this behavior to continue with the next middleware.

Dispatcher::run([
    //Try this, and if it's empty, continue
    (new Middlewares\RequestHandler())->continueOnEmpty(),

    //So we can try that
    (new Middlewares\RequestHandler())->handlerAttribute('other'),
]);

Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.

The MIT License (MIT). Please see LICENSE for more information.

More Repositories

1

psr15-middlewares

Collection of PSR-15 middlewares
400
star
2

awesome-psr15-middlewares

A curated list of awesome PSR-15 HTTP Middleware resources
319
star
3

fast-route

PSR-15 middleware to use FastRoute
PHP
94
star
4

utils

Common utils used by PSR-15 middlewares
PHP
50
star
5

negotiation

PSR-15 middleware to implement content negotiation
PHP
44
star
6

http-authentication

PSR-15 middleware to implement Basic and Digest Http authentication
PHP
36
star
7

whoops

PSR-15 middleware to use Whoops as error handler
PHP
32
star
8

payload

PSR-15 middleware to parse the body of the request with support for json, csv and url-encode
PHP
31
star
9

trailing-slash

PSR-15 middleware to normalize the trailing slash of the uri path
PHP
26
star
10

proxy

PSR-15 middleware to forward requests and return responses
PHP
22
star
11

access-log

PSR-15 middleware to generate access logs
PHP
20
star
12

minifier

Middleware to minify Html, CSS and Javascript responses
PHP
18
star
13

client-ip

PSR-15 middleware to detect the client ip and save it as a request attribute.
PHP
16
star
14

cache

PSR-15 middleware with various cache utilities
PHP
15
star
15

debugbar

PSR-15 middleware to insert PHP DebugBar automatically in html responses
PHP
15
star
16

csp

PSR-15 middleware to add the Content-Security-Policy header to the response
PHP
15
star
17

response-time

PSR-15 middleware to save the response time into the X-Response-Time header
PHP
14
star
18

error-handler

PSR-15 middleware to handle http errors
PHP
14
star
19

https

PSR-15 middleware to redirect to https and adds the Strict-Transport-Security header
PHP
14
star
20

php-session

PSR-15 middleware to create a php session using the request data
PHP
13
star
21

honeypot

PSR-15 middleware to implement a honeypot spam prevention
PHP
13
star
22

firewall

Middleware to provide IP filtering
PHP
12
star
23

geolocation

PSR-15 middleware to geolocate the client using the ip address
PHP
12
star
24

referrer-spam

PSR-15 middleware to block referrer spammers
PHP
12
star
25

cors

PSR-15 middleware to implement Cross-Origin Resource Sharing (CORS)
PHP
12
star
26

image-manipulation

PSR-15 middleware to manipulate images on-demand
PHP
10
star
27

filesystem

PSR-15 middleware to write or read responses from files
PHP
9
star
28

aura-router

PSR-15 middleware to use Aura.Router
PHP
8
star
29

skeleton

A skeleton repository for PSR-15 middleware packages
PHP
7
star
30

encoder

PSR-15 middleware to encode the response body to gzip or deflate
PHP
6
star
31

csv-payload

PSR-15 middleware to parse the CSV body of the request
PHP
6
star
32

reporting-logger

PSR-15 middleware to log server-side reportings
PHP
6
star
33

recaptcha

PSR-15 middleware to use Google reCAPTCHA for spam prevention
PHP
6
star
34

redirect

Middleware to redirect old urls to new urls SEO friendly
PHP
6
star
35

method-override

PSR-15 middleware to override the request method using the X-Http-Method-Override header
PHP
6
star
36

error-response

Middleware to create responses with error status code (4xx-5xx)
PHP
6
star
37

aura-session

PSR-15 middleware to manage sessions using Aura.Session
PHP
6
star
38

uuid

PSR-15 middleware to generate an UUID and save it in the X-Uuid header
PHP
5
star
39

shutdown

PSR-15 middleware to display a 503 maintenance page
PHP
5
star
40

ideas

Need a Middleware or looking for ideas?
5
star
41

json-exception-handler

Middleware to catch exceptions and output them as JSON
PHP
5
star
42

robots

PSR-15 middleware to enable/disable the robots of the search engines
PHP
4
star
43

emitter

Middleware to send (or emit) a PSR-7 response object using header() and echo
PHP
4
star
44

www

PSR-15 middleware to add or remove the www subdomain
PHP
4
star
45

base-path

PSR-15 middleware to remove the prefix from the uri path of the request
PHP
4
star
46

base-path-router

PSR-15 middleware to assign request handlers based on path prefixes
PHP
4
star
47

content-length

PSR-15 middleware to inject the Content-Length header into the response
PHP
3
star
48

lowercase

PSR-15 middleware to convert the URI path to lowercase
PHP
2
star