r/PHPhelp • u/Ok-Fisherman7532 • Jan 21 '25
How decouple method from request?
How can I decouple a method from a request? I’d like to pass a generic object (e.g., a DTO) instead of being tied to a request. This way, I could call that specific method both from an API and from a command. What would be the best approach to achieve this? Thank you
1
Upvotes
View all comments
Show parent comment
4
u/MateusAzevedo Jan 22 '25 edited Jan 22 '25
That code snippet would have been very useful if posted it in the original question...
As far as I know, Laravel doesn't support mapping requests into custom DTOs like Symfony does. You can't use
App\TransferObjects\SignatureRequestDataas the argument type in your controller method (and that's what the error message is telling you).Solution: keep your controller as it was, receiving a standard request or form request object. Create the DTO inside the controller method. Please, don't type the DTO constructor as
__construct(Request | array $params), use eitherarrayor individual values. But you can create a static factory method if you wish.Also,
$this->params = $paramsand$data->all()makes no sense, that's not how DTOs are supposed to be used. If used that way, they won't offer any benefit over associative arrays.It seems that this approach is way over your head and the only thing you really wanted is decoupling, but read somewhere that you need to use a DTO causing all this confusion. The good thing, DTO's aren't needed. To achieve decoupling from request, the only thing needed is to not pass along the
Requestobject but scalar values. Of course that DTO help for many other reasons, but the DTO itself isn't the thing that allows for decoupling. Examples: