mercredi 9 mai 2018

Where to extract logic from controllers?

My goal is to extract all logic into some common place, so I can remove code duplication and decouple my code from the input interface (web, console or whatever).

Let me explain my doubts with an example.

I have a UsersController and createAction. Creating user is made of multiple steps:

  • create row in users table
  • create row in profiles table
  • create row in addresses table
  • create ...
  • send some notification
  • maybe something else in the future.

My first idea is to create something like UserSaver service.

Is that the right naming convention?

To decouple this service from the input interface it would accept some kind of DTO, which would be populated inside a controller, command or whatever, where also input validation would occur.

Inside my service I would have some save/create method that would call repositories and to send the notification I would dispatch some UserCreatedEvent.

At first creating separate service for each part of CRUD (maybe except R) seem like an overkill but I am afraid if I put everything in one UserService its constructor would explode cause of dependencies (like 3 repositories + dispatcher in the case above).

So to update the user I would have UserUpdater and to delete the User UserRemover.

Is that the right design? Are there any other patterns to approach this?

Aucun commentaire:

Enregistrer un commentaire