PHP单一类最佳实践 [英] Best practice on PHP singleton classes
问题描述
可能重复:
谁需要单身人士?
我总是写关于最好的实践,但我也想了解为什么某件事情是最佳做法。
I always write with respect to best practice, but I also want to understand why a given thing is a best practice.
我已经阅读文章(我不幸的是不记得),单例类被优先实例化,而不是使用静态函数进行,并且使用范围解析运算符(:)来访问。所以如果我有一个类包含我所有的工具来验证,简而言之:
I've read on in an article (I unfortunately don't remember) that singleton classes are prefered to be instantiated, rather than being made with static functions and accessed with the scope resolution operator (::). So if I have a class that contains all my tools to validate, in short:
class validate {
private function __construct(){}
public static function email($input){
return true;
}
}
我被告知这被认为是 (或至少警告),因为垃圾收集器和维护等事情。那么单例类作为静态方法的批评是什么意思呢,就是我实例化一个类,我100%肯定我只会一次实例化。对我来说,似乎是做双重工作,因为它已经准备好了。我缺少什么?
I've been told this is considered bad practice (or at least warned against), because of such things as the garbage collector and maintenance. So what the critiques of the "singleton class as static methods" wants, is that I instantiate a class I'm 100% certain I will only ever instantiate once. To me it seems like doing "double work", because it's all ready there. What am I missing?
有什么看法?当然这不是一个生死攸关的问题,但是如果有选择的话,可以做一个正确的方法:)
What's the view on the matter? Of course it's not a life and death issue, but one might as well do a thing the right way, if the option is there :)
推荐答案
php中的一个示例单例类:
在PHP5中创建单例设计模式:Ans 1: _
在PHP5中创建Singleton设计模式:Ans 2:
An example singleton classes in php:
Creating the Singleton design pattern in PHP5 : Ans 1 :
Creating the Singleton design pattern in PHP5 : Ans 2 :
Singleton被认为是坏习惯。
主要是因为其中:如何测试注册表模式或单身人士PHP?
Mainly because of this: How is testing the registry pattern or singleton hard in PHP?
why singletons are evil?
Do you need a dependency injection container
想要阅读更多? :
单例决策图(来源):
这篇关于PHP单一类最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!