2011-11-25 29 views
0

我目前正在構建一個庫,它將用作網站的主存儲引擎。它只是從MySQL數據庫中提取信息,但我想創建變體(使用相同的函數和參數)來從其他存儲系統(如XML或MSSQL)獲取和設置數據,因此不會重新編程如果數據庫類型已更改,則爲必需。另外一個好處是還可以增加安全性來幫助防止SQL注入攻擊。用於執行MySQL和XML查詢的抽象PHP類

我現在遇到的問題是該類的摘要。我不知道如何以適用於不同類型的方式構造它(所以我不能只擁有一個SQL字符串)。有沒有人有任何想法可以提供什麼參數。我正在考慮使用嵌套數組來創建括號併爲查詢定義運算符,但是在使用XML時可以用它來進行直接分析。

回答

1

我希望我沒有誤解你的問題(在這種情況下,我將修改或刪除答案),但如果我正確地得到你:

這取決於你的使用情況,但如果可能,我只是使用與PDO相同的界面。然後,您可以使用PDO驅動程序來處理它們存在的事物。其他程序員可以很容易地理解你的API。

+0

有點,但我試圖使用的東西,它將都在同一個參數,以保持緊密針織。我已經決定返回將是一個數據行的數組(每行都是一個嵌套數組,而在該數組中,鍵是列,值是值)。但PDO看起來很有用,但它不包含XML。原因是因爲我已經爲堅持託管它的人編寫了網站,但是它們太貴而無法升級其託管軟件包。打算使用這個作爲一個快速的解決方法。 – topherg

0

如何使用兩個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 { 
    ... 
}