一个简单的实现方法可以帮助您入门,如下所示:
class db
{
public function __call($function, $arguments)
{
switch($function) {
// implement table handling here
case 'user':
//do something
return $something;
break;
}
}
}
根据您是否想变得复杂,但坚实或简单,但不太灵活,您可能会实施两种不同的策略。简单的策略可能是这样的:
class db
{
protected $operatingTable;
public function limit($limitNumber)
{
return $this->executeQuery("SELECT * FROM ".$this->operatingTable." LIMIT ".$limitNumber); // where executeQuery is a function that runs a query
}
public function __call($function, $arguments)
{
switch($function) {
// implement table handling here
case 'user':
$this->operatingTable='user'; // alternately, but less secure: $this->operatingTable=$function;
return $this;
break;
}
}
}
或者,但更强大:
class db
{
protected $operatingTable;
public function limit($limitNumber)
{
return $this->executeQuery("SELECT * FROM ".$this->operatingTable." LIMIT ".$limitNumber); // where executeQuery is a function that runs a query
}
public function __call($function, $arguments)
{
switch($function) {
// implement table handling here
case 'user':
$user = new user($this); // pass in the database to the object, so the table object can have a reference to the db
return $user;
break;
}
}
}
class baseTableClass
{
protected $db; // an instance of class db
function limit($limitNumber)
{
$db->execute($aStatementDerivedFromThisClassesInformation); // execute a sql command, based on information about the table in the class
}
}
class user extends baseTableClass
{
public function __construct($db) {
$this->db = $db;
}
}
你明白了。要么重载 db 对象,要么创建基本 db 对象和表对象,将大部分智能放在表对象中,确保创建时,表对象存储对 db 对象的引用