Revision: Wed, 27 Nov 2024 11:25:26 GMT
v3.12 – outdated
This version of the documentation is outdated. Consider upgrading your project to Spiral Framework 3.14
Edit this page

Cookbook — Custom HTTP request handler

Spiral is compliant with several community standards, including PSR-7 (HTTP message interfaces), PSR-15 (HTTP server request handlers), and PSR-17 (HTTP factories).

This means that you can use any request handler implementation you want with PSR-15, which means you can choose the solution that works best for your application.

By default, Spiral includes the Spiral\Router\Router class which implements the Psr\Http\Server\RequestHandlerInterface interface and handles HTTP requests. However, if desired, developers can disable the Spiral\Bootloader\Http\RouterBootloader and use an alternative request routing solution.

Fast Route

In this guide, we will show you how to use the FastRoute as an alternative to the default Spiral router. FastRoute is a fast routing library that allows developers to easily route HTTP requests to callback functions.

As an example, we will replace the default spiral router with one based on FastRoute. The implementation is provided by https://github.com/middlewares/fast-route.

Prerequisites

Before you can use FastRoute, you need to install the required packages:

Implementing FastRoute

To use FastRoute with Spiral, you will need to create a custom bootloader to bind the FastRoute implementation to the HTTP server. The bootloader should bind this implementation to our http server. Simply declare Psr\Http\Server\RequestHandlerInterface in SINGLETONS constant.

Here is an example of a FastRoute bootloader:

php
app/src/Application/Bootloader/FastRouteBootloader.php
namespace App\Application\Bootloader;

use FastRoute;
use Middlewares;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Spiral\Boot\Bootloader\Bootloader;
use Psr\Http\Message\ServerRequestInterface;

final class FastRouteBootloader extends Bootloader
{
    protected const SINGLETONS = [
        RequestHandlerInterface::class => [self::class, 'psr15Handler'],
    ];

    private function defineRoutes(FastRoute\RouteCollector $router): void
    {
        $router->addRoute('GET', '/hello/{name}', static function (ServerRequestInterface $request): string {
            $name = $request->getAttribute('name');

            return \sprintf('Hello %s', $name);
        });
    }

    private function psr15Handler(ResponseFactoryInterface $responseFactory): RequestHandlerInterface
    {
        $dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector $r) {
            $this->defineRoutes($r);
        });

        return new Middlewares\Utils\Dispatcher([
            new Middlewares\FastRoute($dispatcher, $responseFactory),
            new Middlewares\RequestHandler(),
        ]);
    }
}

In the example above, the defineRoutes function is used to define the routes that will be handled by FastRoute. In this case, we have defined a single route that matches requests to the /hello/{name} URL and passes the request to a callback function that returns response.

Add this Bootloader to your application:

php
app/src/Application/Kernel.php
public function defineBootloaders(): array
{
    return [
        // ...
        \Spiral\Bootloader\Http\HttpBootloader::class,
        \App\Bootloader\FastRouteBootloader::class,
        // ...
    ];
}

Read more about bootloaders in the Framework — Bootloaders section.

Once you have implemented the FastRoute bootloader and added it to your Spiral application, you will be able to use FastRoute to handle HTTP requests.

Congratulations, now you know how to use a custom implementation of the Psr\Http\Server\RequestHandlerInterface interface in Spiral! By using the FastRoute library or any other PSR-15 compliant library, you can easily swap out the default Spiral router and use an alternative solution to handle HTTP requests. Whether you need to use a different routing library, implement custom request handling logic, or use components from multiple sources, the Spiral Framework's compliance with PSR-15 makes it easy to use a wide variety of request handler implementations in your applications.

So go ahead and start building the best application you can!