Классы отчасти представляют вещи в реальном мире (или даже воображаемые «вещи»), верно? Экземпляр БД представляет соединение с этой БД. Имеет ли модель что-то общее с подключением к базе данных? На самом деле, нет. Я бы предложил включить экземпляры вашего класса базы данных в те классы моделей, которые вы собираетесь написать, потому что модель использует подключение к базе данных для доступа к своим данным, но не является подключение к базе данных.
Относительно Mysqli <-> DBClass: Это действительно зависит от того, чего вы пытаетесь достичь с помощью этого DBClass - расширяет ли он Mysqli некоторыми дополнительными функциями или чем-то еще? Если это не так, не используйте наследование там, иначе вы можете использовать его.
Очень простой пример, просто чтобы дать вам идею: (на самом деле это упрощенная, но определенно не полная версия шаблона ActiveRecord)
abstract class DbTable {
/* An instance of your DBClass (=Database Connection), to be used if no
* other connection is specified. */
protected static $_defaultDbAdapter = null;
/* The db connection to be used by this instance. */
protected $_dbAdapter = null;
/* The name of the table in the database. */
protected $_tableName = '';
public static function setDefaultDbAdapter(DbClass $db) {
self::$_defaultDbAdapter = $db;
}
public function setDbAdapter(DbClass $db) {
$this->_dbAdapter = $db;
}
public function getDbAdapter() {
if (null === $this->_dbAdapter) {
$this->setDbAdapter(self::$_defaultDbAdapter);
}
return $this->_dbAdapter;
}
public function insert(array $data) { /*...*/ }
public function update(array $data, $where) { /*...*/ }
public function delete($where) { /*...*/ }
public function select($where) { /* may e.g. return an array of DbTableRow childclass instances */ }
// ...
}
class Users extend DbTable {
protected $_tableName = 'my_users_table';
}
abstract class DbTableRow {
/* The row itself (may be not yet saved to the db!) */
protected $_data = array();
/* The row as it is in the database (to find differences, when calling save()). */
protected $_cleanData = array();
/* An instance of the table that this row belongs to. */
protected $_table = null;
public function __construct(DbTable $table, array $data = array()) { /*...*/ }
public function save() { /* uses $this->_table->insert()/update() */ }
public function __get($key) { /*...*/ }
public function __set($key, $value) { /*...*/ }
// ...
}
class User extends DbTableRow { }
Использование:
// Make a new connection to the database
$db = new DbClass('...'); // or whatever you name that class...
// Set this connection to be the default connection
DbTable::setDefaultDbAdapter($db);
// Create a new user
$users = new Users();
$user = new User($users);
$user->email = 'test@example.com';
$user->save();