如何将单个MySql连接与多个PHP对象一起使用。

时间:2011-09-18 20:56:49

标签: php oop dependency-injection pdo

我已经经历了很多这方面的例子,但是我读的越多,我就越困惑(对不起!)。我的首要任务是保持简单高效。生成单个MySql连接并与多个PHP对象共享。

// open a db connection 
$dbc = new PDO(.......);

// allow multiple objects to use the same connection

$object_1 = new class_1($dbc);
$object_2 = new class_2($dbc);
$object_3 = new class_3($dbc);

// or should it be passed this way?

$object_1->connection($dbc);
$object_2->connection($dbc);
$object_3->connection($dbc);

// or should each of the classes be getting the connection
// from a singleton type db object? 

// should each object be an extesion of a db class?

// or is there something else I need to consider?

2 个答案:

答案 0 :(得分:1)

// allow multiple objects to use the same connection

$object_1 = new class_1($dbc);
$object_2 = new class_2($dbc);
$object_3 = new class_3($dbc);

// or should it be passed this way?

$object_1->connection($dbc);
$object_2->connection($dbc);
$object_3->connection($dbc);

这两个都是正确的,尽管如果数据库连接是对象工作所必需的,那么将它传递给构造函数是首选方法。

有关此主题的更多信息,请查阅有关依赖注入的文章。

例如:http://martinfowler.com/articles/injection.html

答案 1 :(得分:1)

我更喜欢将Connection Class设为Singleton:

class DBConnection {
    // Store the single instance of DBConnection 
    private static $m_pInstance;

    private function __construct() { ... }

    public static function getInstance()
    {
        if (!self::$m_pInstance)
        {
            self::$m_pInstance = new DBConnection();
        }

        return self::$m_pInstance;
    }
}