Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 and be DRY approach in controllers

I'm developing a small CMS for my company using Symfony2. I really love this framework. I love form classes and reusing them (that's all about forms after all).

But (yes, there is a "but") I'm feeling like I'm doing the same stuff, copy and paste in all controllers. A code duplication that we hate. With all the business logic moved to Services and forms, events, persist actions in Doctrine, all my controllers do the same thing:

  • Get the respository $this->get('mycompany.repository.entity')
  • Dynamically create the form (the logic is inside the form class itself)
  • Validate the form, returning the view or persisting the entity
  • and so on...

What I mean is that controller actions are all the same, just a few characters changes.

How can be DRY with Symfony2 in my controllers? Maybe controller as service (a concept that I discovered only a few days ago) may help?

EDIT: related question (to the first idea suggested by Boo): Symfony2 how to redirect to an action without hardcoding route name?

like image 800
gremo Avatar asked Nov 05 '22 03:11

gremo


1 Answers

There are many ways to get to a more DRY code base:

  1. You could create an abstract BaseController. It could group the code which gets repeated into some private method(s), so every controller extending it could use it. Using private properties you could set the Controller-specific stuff before calling the methods.
  2. You could implement some BaseService so you only need to call this service, set some parameters (like which repository to use) and then have the service do the logic
  3. You could have only one Controller which takes some parameters and define each route to use this controller, passing the specific parameters.

I guess there are even more ways when thinking about it.

I find idea 1 very elegant while 3 also have some advantages. The second approach is kind of blury, especially as you again need dublicated code (even if it will be much less, it's far from optimal). Idea 1 is in sync with the OO idea and it communicates it's intent well. To sum it up, I would use a BaseController!

like image 195
Sgoettschkes Avatar answered Nov 15 '22 09:11

Sgoettschkes