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

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

问题描述


可能重复:

谁需要单身人士?

我总是写关于最好的实践,但我也想了解为什么某件事情是最佳做法。

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?


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

why singletons are evil?

一个好的方法:依赖注入

可重用性演示:将您的PHP代码解耦为可重用性

您是否需要依赖注入容器? a>

Do you need a dependency injection container

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

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

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

想要阅读更多? :


使用PHP PDO的数据库抽象类设计

将单个作为微博网站的一个很好的设计模式?

修改课程封装而不是继承

如何从另一个类访问对象?

使用单身人士的测试代码

单例决策图(来源):

这篇关于PHP单一类最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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