如何使用兩個OOP繼承分支:用於查詢和數據?
class query {
protected $row_classname = 'row';
protected $params = array();
protected $result;
public function bind_param($name, $value) { ... }
public function execute() {
//here go some common cache issues, param checks, etc.
$this->run_query();
}
public function get_result() {
//you can map it to $this using __get and __set
return $this->result;
}
abstract function run_query();
}
class sql_query extends query {
protected $pdo_connection;
protected $pdo_statement;
protected function run_query() {
$this->pdo_statement = $this->get_pdo()->prepare($this->get_statement());
$this->pdo_statement->setFetchMode(PDO::FETCH_CLASS, $this->row_classname);
$this->bind_params_to_pdo_statement();
$this->pdo_statement->execute();
$this->result = $this->pdo_statement->fetchAll();
}
}
class select_users_by_id extends sql_query {
protected $row_classname = 'user_row';
protected function get_statement() {
return 'SELECT * FROM users WHERE id = :id';
}
}
//memcached branch
class memcached_query extends query {
protected function run_query() {
$this->result = new $this->row_classname;
$results = $this->action();
foreach($results AS $k => $v) {
$this->result->$k = $v;
}
}
abstract protected function action();
}
class get_user_by_id extends memcached_query {
protected $row_classname = 'user_row';
protected function action() {
$this->get_memcached_handler()->get_by_key($this->params['key']);
}
}
//usage in project
...
$users_by_id = new select_users_by_id();
$users_by_id->bind('id', 14);
$users_by_id->execute();
var_dump($users_by_id->get_result()->name);
...
//user_row branch
class row {
protected $row = array();
public function __set($name, $value) {
$this->row[$name] = $value;
}
public function __get($name) {
return $this->row[$name];
}
}
class user_row extends row {
...
}
有點,但我試圖使用的東西,它將都在同一個參數,以保持緊密針織。我已經決定返回將是一個數據行的數組(每行都是一個嵌套數組,而在該數組中,鍵是列,值是值)。但PDO看起來很有用,但它不包含XML。原因是因爲我已經爲堅持託管它的人編寫了網站,但是它們太貴而無法升級其託管軟件包。打算使用這個作爲一個快速的解決方法。 – topherg