xis's avatar
Level 1

Create new model outside controller

Hi there,

I have an application that manages the workers for employment agencies. There are 2 ways of creating new workers:

  • Manually creating a worker by filling in their details (handled by a CRUD resource on the backend in WorkerController)
  • Bulk creating by uploading a CSV file where each row is a worker (Handled by an import handler --> not WorkerController)

I am wondering what the best way is to handle duplicate code? I do not want to write 2 identical functions in both WorkerController and my import handler that create workers. However, if I am not mistaken it is bad practice to directly call a function from a controller (=WorkerController) from my import handler. Should I be using a trait that I use in both WorkerController and my import handler? Should I write a worker service/repository that I can then use both in my WorkerController and import handler (this seems to me the best option)? I multiple options but I am curious what the best option would be.

Thanks in advanced!

0 likes
3 replies
martinbean's avatar
Level 80

@xis Extract the common logic to a service class. You can then re-use this class in both your controller and worker. If you need to update the logic, you only need to update it in one place.

2 likes

Please or to participate in this conversation.