Symfony2并且是控制器中的DRY方法 [英] Symfony2 and be DRY approach in controllers

查看:152
本文介绍了Symfony2并且是控制器中的DRY方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Symfony2为我公司开发一个小CMS。我真的很喜欢这个框架。我喜欢表单课,并重用它们(这些都是关于表单)。

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:


  • 获取相应的 $ this-> get('mycompany。

  • 动态创建表单(逻辑在表单类内)

  • 验证表单,返回视图或坚持实体

  • 等等...

  • 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.

如何 DRY 在我的控制器中有Symfony2?也许控制器作为服务(一个我几天前才发现的概念)可能有帮助?

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?

编辑:相关问题(第一个想法Boo建议): Symfony2如何重定向到一个没有硬编码路由名称的动作?

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

推荐答案

有很多方法可以获得更多的DRY代码库: / p>

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


  1. 您可以创建一个抽象的BaseController。它可以将重复的代码分组到一些私有方法中,因此扩展它的每个控制器都可以使用它。使用私有属性,可以在调用方法之前设置Controller特定的东西。

  2. 您可以实现一些BaseService,因此您只需要调用此服务,设置一些参数(如使用哪个存储库)然后让服务执行逻辑

  3. 您可以只有一个控制器需要一些参数,并定义每个路由以使用此控制器,传递具体参数。

我想有更多的方法来考虑它。

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

我发现主意1非常优雅而3也有一些优势。第二种方法是一种不礼貌的情况,特别是当你再次需要公开代码(即使它会少得多,这远远不是最佳的)。 Idea 1与OO的想法是一致的,它的意图很好。总结一下,我会使用BaseController!

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!

这篇关于Symfony2并且是控制器中的DRY方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆