cololaradev's avatar

Extending Request Class

Hello,

I´m trying to extend the Request Class.

Use Case: There is a middleware which determines a microservice url from the request path. This microservice url should be available later on in a controller. I thought it could be a good option to place it to the request class.

I don´t find any documentation how to achieve this.

Many thanks.

0 likes
4 replies
martinbean's avatar

@cololaradev Add the method as a macro in a service provider:

Request::macro('getMicroserviceUrl', function () {
    // Code to determine and return microservice URL
});

You can then use this as a normal method on the Request class elsewhere in your application:

Request::getMicroserviceUrl();
cololaradev's avatar

@martinbean Thanks. I will have a look at macros also. In the meanwhile I found another solution.

Extending the illuminate request class and register the custom request class as singleton inside the AppServiceProvider. This should do the trick.

$this->app->singleton(Request::class, function () {
     return Request::capture();
});

$this->app->alias(Request::class, 'request');

3 likes

Please or to participate in this conversation.