I develop web applications with PHP. I have many classes using a database connection.
This is the structure i generally use;
class SomeClass {
private $db;
function __construct(mysqli $db) {
$this->db = $db;
}
function SomeFunction() {
$this->db->query(...);
}
}
And this is what i thought to use;
class Common {
public static DB = new mysqli(...);
}
class SomeClass {
function SomeFunction() {
Common::DB->query(...);
}
}
There are two parts of my question;
Which one is better practice? If i use first one, i have to pass database object to every class uses db. If i use second one, every class uses db will be dependent to Common class.
I made examples simpler. Actually i have a Database class extends mysqli and a DatabaseTableManager class using Database class. I add GetTable() function to Database class. I create DatabaseTableManager objects in this function (
return new DatabaseTableManager($this, $tableNameFromArgument)
) so i do not have to pass db object every time. In DatabaseTableManager class, i built some queries to make my job easier.
E.g. to insert a record to a table;
$DB = new Database(...);
$myTable = $DB->GetTable('myActualTableNameInDatabase');
$myTable->Insert( array('col1' => 'val1', 'col2' => 'val2') );
So i use this class a lot in my other classes. Naturally all these classes become dependent to DatabaseTableManager class. What is the better solution?