PHP 函数组织
我正在编写一个非常基本的 php 应用程序,并创建了一大堆函数来执行各种操作,例如 display_user_nav()、display_user_list() 等。我想要一种以逻辑方式组织这些函数的方法。我真正需要的是像 ruby 模块这样的东西,但我还没有找到 php 的等价物。我还觉得从编程的角度来看,它们不属于类,因为我已经有一个 User 对象来包含一个用户的信息,并且不希望每当我想使用它们时都必须创建和存储新对象。
我现在正在做什么:
display_user_table()
display_user_edit_form()
我想要做什么(有点像 Ruby):
User_Functions::Display::Table()
User_Functions::Display::Edit_Form()
任何建议都会受到赞赏。
I am writing a pretty basic php app and have created a pretty big mess of functions to do various things, e.g. display_user_nav(), display_user_list() etc. I want a way to organize these in a logical way. What I really need is something like a ruby module, but I haven't been able to find a php equivalent. I also feel that from a programming standpoint they don't belong in classes, as I already have a User object to contain information for one user, and don't want to have to create and store a new object whenever I want to use them.
What I am doing now:
display_user_table()
display_user_edit_form()
What I kind of want to be able to do (sort of like Ruby):
User_Functions::Display::Table()
User_Functions::Display::Edit_Form()
Any suggestions are appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用 PHP 5.3+,则可以使用 命名空间。
因此,您可以命名您的函数(命名空间分隔符是
\
):但是,似乎为此使用类并不是一个坏主意。如果您觉得显示函数并不真正属于
User
(就像许多人认为序列化方法在目标对象中没有意义一样),您可以创建一个如下类:If you are using PHP 5.3+, you have namespaces available.
So you can name your functions (the namespace separator is
\
):However, it seems like using a class for this wouldn't be a bad idea. If you feel that display functions don't really belong to
User
(the same way many people think serialization methods don't make sense in the target objects), you can create a class like this:抽象类怎么样?还是单身人士?这是组织代码的好方法
how about Abstract Classes!? or singletons? thats a good way to organize your code
好吧,您可以将它们分解为帮助器类,例如:
帮助器的体系结构可能更复杂,并根据您的类的操作方式实现流畅的接口或达到此效果的东西。
另一种方法可能是将装饰器附加到您的对象以执行这些功能。
Well you could break them out into helper classes for example:
The architecture of the helpers could be more complexx and implement a fluid interface or something to that effect depending on how your classes operate.
Another approach might be to attach decorators to your objects to perform these functions.
根本不应该有这样的函数,而应该有一个负责所有 HTML 输出的模板。
问题是您以错误的方式使用函数:创建一个函数只是为了多次重复某些操作。
不要将函数仅用于单一操作。
There shouldn't be such functions at all but a template that takes care of all HTML output.
The problem is you are using functions in a wrong way: make a function only to repeat some operations more than once.
Do not use a function for just single operation.