Writing THIN Controller, FAT model using Event Dispatcher in Symfony
After reading Robert Martin(Uncle Bob) The Clean Architecture, I was wondering how to apply these concepts to my projects. As a first step i decided to implement “thin controller and fat models” philosophy in my project.
I used Symfony Event Dispatcher component for this purpose and It worked fine to me.
Business logic should always be in the models or services. The controller is just an adapter.
Placing business logic into models/services make our code callable from multiple places in our app. It also makes the code easier to test.
How (the 4 steps)
I used Symfony Event dispatcher component for this purpose. My approach to apply the concept are these steps:
Step 1: Create an Event class that will hold our entity/entities and action type i.e create, update, delete etc.
Step 2: Create an abstract Controller that extends Symfony Abstract Controller.
Step 3: Let’s say we want to implement a Controller for POST entity…
Step 4: Now add an Event Listener which will be listen to all 3 events
Declare the Listener class as a service.
Note, It’s not necessary to implement all 3 methods.
Now we have thin controller and all our application logic is in Listener class. You can also called services class from here by injecting those services into the listener class. But the aim was to move business logic out of controller which is achieved.
This is WIP, you feedback will improve it further..