Jose Gabrielle Rivera
jgrivera.dev

jgrivera.dev

RequestHandled Event in Lumen using After-Middleware

Jose Gabrielle Rivera's photo
Jose Gabrielle Rivera
·Jul 19, 2021·

2 min read

Problem

I was looking for the RequestHandled event in Lumen. Unfortunately, I was not able to find it.

This event can be found in Laravel through the Illuminate/Foundation/Http/Events namespace. Lumen does not have reference of this namespace though, since it has a different dependency. To compensate, we can make use of an after-middleware instead.

Solution

Reference the code for Laravel's RequestHandled event. We will be using this in our middleware later:

<?php

namespace App\Events\Http;

class RequestHandled
{
    /**
     * The request instance.
     *
     * @var \Illuminate\Http\Request
     */
    public $request;

    /**
     * The response instance.
     *
     * @var \Illuminate\Http\Response
     */
    public $response;

    /**
     * Create a new event instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Http\Response  $response
     * @return void
     */
    public function __construct($request, $response)
    {
        $this->request = $request;
        $this->response = $response;
    }
}

Here is the code for our RequestHandleMiddleware after-middleware.

<?php

namespace App\Http\Middleware;

use App\Events\Http\RequestHandled;
use Closure;

class RequestHandleMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        event(new RequestHandled($request, $response));

        return $response;
    }
}

It fires after all middleware have finished processing. Here, it simply passes the request and response to our own homemade RequestHandled event. The event is then passed to all listeners.

Do not forget to register the middleware in your app/bootstrap.php, like so:

<?php

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

$app->middleware([
    App\Http\Middleware\RequestHandleMiddleware::class
]);

Closing Thoughts

Now, you can go ahead and listen to our homemade RequestHandled event! This taught me to look at how something is implemented under-the-hood. We can definitely implement the missing parts on our own; especially when the source code is available for us to read.

Feel free to discuss any performance complications of this method if you have found any. This article was inspired by a discussion made here .

 
Share this