PHP单例类的最佳实践 [英] Best practice on PHP singleton classes

查看:134
本文介绍了PHP单例类的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

谁需要单身人士?

练习,但我也想了解为什么给定的东西是最佳做法。

文章(我不幸地不记得)单例类优先被实例化,而不是使用静态函数,并使用范围解析操作符(::)访问。所以如果我有一个类包含所有我的工具来验证,总之:

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中创建Singleton设计模式: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被认为是不良做法。

如何测试注册表?

Mainly because of this: How is testing the registry pattern or singleton hard in PHP?


为什么单身人士是邪恶的?

一种好方法:依赖注入

有关可重用性的演示:将您的PHP解除连接可重用代码

您是否需要依赖注入容器

静态方法与单身人士都不选择

清洁代码谈话 - 全球国家和单身人士

反转的控制容器和依赖注入模式

? :


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