好吧,这只是一个简单的问题,我可能会有一些松懈,但我只是在寻找一点指导,因为我完全是自学的。我读了很多书,也试着做了很多构建--我想说,我正进入一个很好的中级阶段,掌握php、mysql和一般的web知识--绝对不是很高级,也不是过于自信--我还在学习。
我真的在尝试用PHP语言解决OOP问题,所以我想为MySQL创建一个很好的精益数据库包装器,就像MySQL一样,我对MySQL最满意,而且我看不出有任何理由要使用其他数据库。我不想在设计中创建任何类型的可移植性--我希望它特定于我的数据库;所以我不想使用PDO。
因此,一开始我的问题是,我是否应该创建一个扩展mysqli的类,然后为我的数据库表创建扩展该基本数据库类的模型类?那么class->child = mysqli->DbBase->UsersModel?这将需要在类中使用大量的$this语句,不是吗?
或者我应该实例化一个mysqli类并将其传递给DbBase?
发布于 2012-03-10 07:27:39
类可以表示现实世界中的事物(甚至是想象中的“事物”),对吧?数据库的实例表示到该数据库的连接。模型与数据库连接有什么共同之处吗?不怎么有意思。我建议在将要编写的模型类中包含数据库类的实例,因为模型使用数据库连接来访问它的数据,但不是一种数据库连接。
关于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();发布于 2012-03-10 07:37:19
如果您打算使用OOP,我强烈建议您使用PDO,因为它是MySQL库的最新的OO实现。我不认为PDO-MySQL比MySQLi更不是MySQL特有的。
在任何情况下,您都不应该扩展PHP的类在这种情况下,您应该保留一个带有数据库连接的对象作为您的类的属性。
您还应该研究Singleton设计模式,它在这些情况下非常有用。看看今天的这篇文章:Move out mysql connection into another class
发布于 2012-03-10 08:02:03
如果你真的想学习和理解OOP,那么我认为你应该开始学习一些PHP框架(比如Zend框架),并阅读它的源代码。我从他们那里学到了很多东西。
https://stackoverflow.com/questions/9642262
复制相似问题