nikic / FastRoute

Fast request router for PHP
Other
5.13k stars 444 forks source link

How to apply middelware to FastRoute routes? #262

Closed Merchant6 closed 1 year ago

Merchant6 commented 1 year ago

I am working on mini-framework based on Swoole, I implemented FastRoute to route request to their appropriate handlers. The router is working perfectly but I am wondering how would I apply middlewares. I delve into the Slim Framework FastRoute implementation and how they apply middlewares, I did get a hang of it but I am still confused.

Here's my Router class:

class Router
{

    public function __construct(public Request $request, public Response $response)
    {

    }

    public function router() : void
    {
        /*
        |--------------------------------------------------------------------------
        | Implementing FastRoute simple dispatcher
        |--------------------------------------------------------------------------
        */
        $dispatcher = simpleDispatcher(function(RouteCollector $routeCollector){

            $routeCollector->get('/', [new ExampleController($this->request), 'index']);
            $routeCollector->get('/get', [new ExampleController($this->request), 'get']);
        });

        $this->response->header('Content-Type', 'application/json');

        $httpMethod = $this->request->server['request_method'];
        $uri = rawurldecode($this->request->server['request_uri']);

        $routeInfo = $dispatcher->dispatch($httpMethod, $uri);

        switch ($routeInfo[0]) {
            case Dispatcher::NOT_FOUND:
                // ... 404 Not Found
                $this->response->status(404);
                $this->response->end('Not Found');
                break;
            case Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $routeInfo[1];
                // ... 405 Method Not Allowed
                $this->response->status(405);
                $this->response->end('Method not allowed');
                break;
            case Dispatcher::FOUND:
                $handler = $routeInfo[1];
                $vars = $routeInfo[2];

                $responseText = $handler($vars);
                $this->response->status(\App\Core\Response::$status ?? 200);
                $this->response->end($responseText);
                break;
        }
    }
}