全球或单身人士数据库连接? [英] Global or Singleton for database connection?

查看:97
本文介绍了全球或单身人士数据库连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中使用单例而不是全局数据库连接有什么好处?我觉得使用单例而不是全局使代码不必要地复杂。



全球代码



 code> $ conn = new PDO(...); 

function getSomething()
{
global $ conn;



}



使用Singleton的代码



  class DB_Instance 
{
private static $ db;

public static function getDBO()
{
if(!self :: $ db)
self :: $ db = new PDO(...);

return self :: $ db;
}
}

函数getSomething()
{
$ conn = DB_Instance :: getDBO();



}

如果有更好的方法初始化数据库连接,而不是全局或单身,请提到它,并描述它对全球或单身人士的优势。

解决方案

我知道这是旧的,但Dr8k的答案是>几乎那里。



当你正在考虑编写一段代码时,假设它会改变。这并不意味着你将来会在某些时候提出这种变化,而是要进行某种形式的改变。



使其成为减轻未来变化的痛苦的一个目标:全球是危险的,因为在一个地方很难管理。如果我想在将来知道数据库连接上下文怎么办?如果我想要每五年被关闭并重新打开自己,该怎么办?如果我决定为了扩展我的应用程序,我想使用10个连接池?还是可配置数量的连接?



单身工厂为您提供了灵活性。我设置了很少的额外的复杂性,并获得不仅仅是访问相同的连接;我有能力以简单的方式改变这种连接如何传递给我。



请注意,我说单身工厂简单地单身人士。单身人士与全球人士之间存在着宝贵的差异。因此,没有理由有一个单身连接:为什么你可以花时间设置,当你可以创建一个常规的全球?



什么工厂得到你是一个为什么要获得连接,另一个地方可以决定你将要获得的连接(或连接)。



示例



  class ConnectionFactory 
{
private static $ factory;
private $ db;

public static function getFactory()
{
if(!self :: $ factory)
self :: $ factory = new ConnectionFactory(...);
return self :: $ factory;
}

public function getConnection(){
if(!$ this-> db)
$ this-> db = new PDO );
return $ this-> db;
}
}

函数getSomething()
{
$ conn = ConnectionFactory :: getFactory() - > getConnection();



}

然后,在6个月的时间里,当你的应用程序超级有名,得到dugg和slashdotted并且您决定需要多个连接,所有您需要做的是在getConnection()方法中实现一些池。或者如果您决定要实现SQL日志记录的包装器,则可以传递PDO子类。或者如果您决定在每次调用时都需要新的连接,那么可以这么做。它是灵活的,而不是刚性的。



16行代码,包括大括号,这将节省你几个小时和几个小时的重构到一个类似的东西。 / p>

请注意,我不认为这是Feature Creep,因为我在第一轮中没有执行任何功能实现。它是边界线未来的蠕变,但在某种程度上,为今天明天编码的想法总是对我而言是不好的。


What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex.

Code with Global

$conn = new PDO(...);

function getSomething()
{
    global $conn;
    .
    .
    .
}

Code with Singleton

class DB_Instance
{
    private static $db;

    public static function getDBO()
    {
        if (!self::$db)
            self::$db = new PDO(...);

        return self::$db;
    }
}

function getSomething()
{
    $conn = DB_Instance::getDBO();
    .
    .
    .
}

If there's a better way of initializing database connection other than global or singleton, please mention it and describe the advantages it have over global or singleton.

解决方案

I know this is old, but Dr8k's answer was almost there.

When you are considering writing a piece of code, assume it's going to change. That doesn't mean that you're assuming the kinds of changes it will have hoisted upon it at some point in the future, but rather that some form of change will be made.

Make it a goal mitigate the pain of making changes in the future: a global is dangerous because it's hard to manage in a single spot. What if I want to make that database connection context aware in the future? What if I want it to close and reopen itself every 5th time it was used. What if I decide that in the interest of scaling my app I want to use a pool of 10 connections? Or a configurable number of connections?

A singleton factory gives you that flexibility. I set it up with very little extra complexity and gain more than just access to the same connection; I gain the ability to change how that connection is passed to me later on in a simple manner.

Note that I say singleton factory as opposed to simply singleton. There's precious little difference between a singleton and a global, true. And because of that, there's no reason to have a singleton connection: why would you spend the time setting that up when you could create a regular global instead?

What a factory gets you is a why to get connections, and a separate spot to decide what connections (or connection) you're going to get.

Example

class ConnectionFactory
{
    private static $factory;
    private $db;

    public static function getFactory()
    {
        if (!self::$factory)
            self::$factory = new ConnectionFactory(...);
        return self::$factory;
    }

    public function getConnection() {
        if (!$this->db)
            $this->db = new PDO(...);
        return $this->db;
    }
}

function getSomething()
{
    $conn = ConnectionFactory::getFactory()->getConnection();
    .
    .
    .
}

Then, in 6 months when your app is super famous and getting dugg and slashdotted and you decide you need more than a single connection, all you have to do is implement some pooling in the getConnection() method. Or if you decide that you want a wrapper that implements SQL logging, you can pass a PDO subclass. Or if you decide you want a new connection on every invocation, you can do do that. It's flexible, instead of rigid.

16 lines of code, including braces, which will save you hours and hours and hours of refactoring to something eerily similar down the line.

Note that I don't consider this "Feature Creep" because I'm not doing any feature implementation in the first go round. It's border line "Future Creep", but at some point, the idea that "coding for tomorrow today" is always a bad thing doesn't jive for me.

这篇关于全球或单身人士数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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