Symfony2 and be DRY approach in controllers

∥☆過路亽.° 提交于 2020-01-13 10:16:29

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/9693513/symfony2-and-be-dry-approach-in-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!