Laravel Controllers & Services
I have been coding a project for a while, and because of its complexity, sometimes I get confused about my own approach.
I would like to shared some of my intentions and code, so we can discuss about it. Hope it will be useful for more people.
I define two kind of "master" controllers:
- Default Controller: extends the base controller (routing controller from Illuminate), and holds the responsibility for sending back the response without any knowledge about the data/implementation.
- Action Controller: extends the default controller, and holds the responsibility to validate an incoming request without any knowledge about the validation rules/messages.
I use the default controller for controllers that does not require any validation. For example, the page for list registered users.
On the other hand, the action controller is used by any controller that required validation. For example, the action of store user on DB.
I created an abstract class to help me execute specialised services. A service is a mix between Controller and Models. The service should receive parameters or attributes, execute the appropriated methods in the models, and return it.
The service knows nothing about the request, so the controller should "prepare/normalise" the data before sending it to the service.
Example: store a user on DB; update user settings; send invoice to payment provider; etc.
This approach helps me to have very specified and small services, so it's much simple to extend/change the implementation without collateral effects. Also, for testing it's pretty easy!
- Some controllers require multiple services call. For example, when the user submit a POST request into /settings, 4 (four) services are invoked, each one with his own implementation. This approach make any sense for you?
- Non-complex services usually perform only CRUD operations, like Get, Store, List, Destroy. But some services requires more complex operations, and sometimes, it's almost a business process. Should I create another layer called Processes to handle this cases?
- My services are returning the Model in almost all the cases. This way, I can set my response according to the request (if JSON request, returns only the data. If view request, returns paginated). This is a good practice?
- Right now, my services handle only it's own model implementation. But, for few specific cases, my services should execute other services. This is the case where I should call a Process execution instead of Service? I really don't like to handle multi-services call into Controller level.
I appreciate your help, and hope this could be useful for others Laravel developers. If something is not clearly, let me know!