【问题标题】:How do I use a single MySql connection with multiple PHP objects.如何将单个 MySql 连接与多个 PHP 对象一起使用。
【发布时间】:2011-11-19 20:01:29
【问题描述】:

我已经阅读了很多这方面的例子,但是我读的越多,我就越感到困惑(对不起!)。我的首要任务是保持简单和高效。生成单个 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?

【问题讨论】:

    标签: php oop dependency-injection pdo


    【解决方案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

    【讨论】:

    • 谢谢!我被引导相信以这种方式将一个对象传递给另一个对象会导致它被复制而不是真正传递。这意味着以某种方式降低效率或导致其他问题。有什么想法吗?
    • 在 PHP4 中它被复制,在 PHP5 中对象总是通过引用传递。但是,除非您专门通过引用传递变量,否则仍会复制变量。
    【解决方案2】:

    我更喜欢将连接类设为 Singlton:

    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;
        }
    } 
    

    【讨论】:

    • 谢谢!我开始认为这也是我想走的路。我知道这听起来很愚蠢,但我能问一下你是如何从使用它的类中调用连接的吗?你是否使用任何类型的破坏来关闭连接?
    • 坦率地说,我在 ASP.NET 中使用它而不是在 PHP 中。我从某个站点复制了这段代码..我认为它应该会有所帮助。
    猜你喜欢
    • 2012-02-22
    • 1970-01-01
    • 2012-11-16
    • 2011-07-05
    • 2020-10-05
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 2013-01-24
    相关资源
    最近更新 更多