開始するための実装が簡単な方法は、次のようになります。
class db
{
public function __call($function, $arguments)
{
switch($function) {
// implement table handling here
case 'user':
//do something
return $something;
break;
}
}
}
複雑でしっかりしたものにするか、シンプルで柔軟性の低いものにするかによって、2 つの異なる戦略を実装できます。簡単な戦略は次のようになります。
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 オブジェクトへの参照を格納するようにします。