PHP:MVC 和 DRY

发布于 2024-09-01 01:23:19 字数 72 浏览 3 评论 0 原文

关于控制器的问题。 控制器可以在动作中调用它自己的类方法吗?

编辑: 哦,对不起。我的意思是我不想重复自己。 :)

Question about controllers.
Can controller call it`s own class methods inside an action?

EDIT:
Oh sorry. I meant I dont want to repeat myself. :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

偏爱你一生 2024-09-08 01:23:19

除非您使用某种模糊的框架以某种方式阻止这种情况,否则您应该能够从类/实例中调用方法,无论该类/实例是控制器还是其他东西。

如果您发现自己编写的代码需要在多个控制器之间重用,则可以考虑编写一个 BaseController 并将通用功能移至此一个中,或者更好地将通用功能分离到辅助类中,然后您可以实例化并按需调用。基本上,如果您需要所有控制器中的某些内容,请将其移至 BaseController。如果您在某些控制器中需要它,请将其设为助手。如果您只需要在一个特定控制器中使用它,请将其保留在那里。

Unless you are using some obscure framework preventing this somehow, you should be able to call methods from within a class/instance, regardless of the class/instance being a Controller or something else.

If you find yourself writing code that needs to be reused across multiple controllers, you could consider writing a BaseController and move common functionality into this one or -better imho- separate common functionality into helper classes, which you can then instantiate and call on demand. Basically, if you need something in all controllers, move it to a BaseController. If you need it in some controllers, make it a helper. If you only need it in one specific controller, keep it there.

喜你已久 2024-09-08 01:23:19

为什么不呢?

这完全取决于你,但我真的不明白有什么理由避免 DRY(笑)。 MVC 的意义是分离控制器/模型/视图,仅此而已:)

编辑:
仍然是的,控制器可以在操作中调用它自己的方法。好的做法是为操作方法指定名称,例如 action_something 或 some_action,并拥有一个稍后扩展的“基本”控制器。喜欢;

Controller
Controller_Application extends Controller
Controller_Layout extends Controller_Application

第一个是某种“抽象”(面向框架),其他则负责应用程序逻辑。所以稍后你会......

Controller_Forum extends Controller_Layout
Controller_News extends Controller_Layout
Controller_Ajax extends Controller_Application

取决于你想要使用某些控制器的目的。

这一切都取决于你;您可以将自己的方法放在您想要的任何地方,并从您想要的任何地方调用它们:)

Why not?

It's all up to you, but I really don't see the reason to avoid DRY ( LOL ). The sense of MVC is to have separated controller / model / view, nothing else :)

EDIT:
Still yes, controller can call it's own methods inside of actions. Good practice would be to give action methods names like action_something or something_action, and have a 'base' controller which you'd extend later. Like;

Controller
Controller_Application extends Controller
Controller_Layout extends Controller_Application

where the first one would be some kind of 'abstraction' (framework-oriented) and others would take care of application logics. So later you'd have ...

Controller_Forum extends Controller_Layout
Controller_News extends Controller_Layout
Controller_Ajax extends Controller_Application

depending on what you want to use certain controller for.

It's all up to you; you can put your own methods where ever you want to and call them from where ever you want to :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文