dvmian's avatar

Should I pass $request to service class?

I have many classes which use Request instance. Now, here is my question: Is it good way to pass this instance directly to service class or better way is extract data from request in Controller and then pass it to service?

0 likes
2 replies
martinbean's avatar

@dvmian Well if you pass a request instance to your service classes, then those service classes will only every be usable in a HTTP context.

If you want your service classes to be usable in other contexts (console commands, queued jobs)—which you should do, as that‘s the entire point of service classes—then yeah, pull the data out of the request and pass it as arguments to your service classes.

5 likes
automica's avatar

I would usually access Request $request via the controller method

eg

public function foo(Request $request) 

and the pass down the parameters the service class needs rather than passing it the whole request object.

eg

$bar = (new ServiceClass())->someMethod($request->argument, $request->secondArgument);

I prefer passing in using DI as that makes the methods easier to test.

TBH I don't think there is a really issue if you want to use Request directly, but this will only work if the class is called via HTTP.

2 likes

Please or to participate in this conversation.