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

查看:26
本文介绍了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 中创建单例设计模式: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 中硬测试注册表模式或单例?

为什么单身是邪恶的?

一个好方法:依赖注入

关于可重用性的演示:解耦您的 PHP 代码可重用性

你需要依赖吗注射容器

静态方法 vs 单例不选

清洁代码会谈 - 全局状态和单身人士"

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

想阅读更多?:

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

对于微博网站来说,单例模式会是一个很好的设计模式吗?

修改类进行封装的继承

如何从另一个班级?

测试使用单例的代码

单例决策图(来源):

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

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