patternphpMinor
MySQL database connection in the constructor
Viewed 0 times
thedatabasemysqlconstructorconnection
Problem
I'm an absolute beginner in PHP OOP in search of the "Holy Grail" of connecting to MySQL database once and reusing this connection for the whole site.
classes/db.php
classes/users.php
users.php
My doubts are mostly on the
It seems to be an easy way to have the connection available, but I read somewhere that instantiate the db connection in the constructor is a bad idea. Can you explain why, and if there's a better way to have the db connection easily available in every class that needs it?
I read a similar question here, but I can't understand the abstraction/holding reference/singleton suggestion from the accepted answer, and the lack of a full practical example doesn't help me.
classes/db.php
' . mysql_error());
mysql_select_db(DATABASE, $connection) or die('Database error -> ' . mysql_error());
}
}
?>classes/users.php
users.php
read();
?>
';
foreach($users as $user){
echo '' . $user['use_name'] . '';
}
echo '';
}
?>My doubts are mostly on the
Users class part:function __construct(){
$db = new DB();
}It seems to be an easy way to have the connection available, but I read somewhere that instantiate the db connection in the constructor is a bad idea. Can you explain why, and if there's a better way to have the db connection easily available in every class that needs it?
I read a similar question here, but I can't understand the abstraction/holding reference/singleton suggestion from the accepted answer, and the lack of a full practical example doesn't help me.
Solution
A better practice is passing a created
DB instance to the Users class. Imagine that you have a Products class, an Orders class etc. Will all of their constructors create a separate MySQL connection? It doesn't look a good idea since all of them could use the same database connection. class Users {
private $db;
public function __construct($db) {
$this->db = $db;
}
....
}
class Products {
private $db;
public function __construct($db) {
$this->db = $db;
}
....
}
$db = new DB();
$users = new Users($db);
$products = new Products($db);Code Snippets
class Users {
private $db;
public function __construct($db) {
$this->db = $db;
}
....
}
class Products {
private $db;
public function __construct($db) {
$this->db = $db;
}
....
}
$db = new DB();
$users = new Users($db);
$products = new Products($db);Context
StackExchange Code Review Q#5732, answer score: 3
Revisions (0)
No revisions yet.