How do I use a single MySql connection with multiple PHP objects.
I have been going through lots of examples on this, but the more I read the more I get confused (sorry!). My priority is keep it simple and efficient. Generate a single MySql connection and share it with multiple PHP objects.
// 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($db开发者_StackOverflow中文版c);
// 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?
// 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);
Both of these are correct, although if database connection is necessary for an object to work, then passing it to constructor is the preferred way.
For more information on this topic look up articles on Dependency Injection.
For example: http://martinfowler.com/articles/injection.html
I preffer to make Connection Class as 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;
}
}
精彩评论