2011-05-03 23 views
0

我有一個包含2個函數的類「測試」,一個用於創建預處理語句,另一個用於執行一次或多次。問題是我如何在第一個中設置綁定並在其他函數中填寫變量。PDO在多種功能中的使用 - 重複使用準備好的語句

class test { 

    private static $moduleSql = "SELECT 
              id, 
              module 
             FROM 
              phs_pages 
             WHERE 
              prettyurl = :prettyUrl AND 
              mainId = :mainId 
              "; 

    private static function pre() { 
     $db = Db_Db::getInstance(); 
     self::$preModuleSql = $db->prepare(self::$moduleSql); 
     self::$preModuleSql->bindParam(':prettyUrl', $prettyUrl); 
     self::$preModuleSql->bindParam(':mainId', $mainId); 
    } 

    private static function getClassByDb($mainId = 0, $id = 0) { 
     $prettyUrl = self::$parts[$id]; 
     self::$preModuleSql->execute(); 
     self::$preModuleSql->debugDumpParams(); 
     $result = self::$preModuleSql->fetch(PDO::FETCH_ASSOC); 

     // get lower level classes 

     if (isset(self::$parts[$id + 1])) { 
      self::getClassByDb($result['id'], $id + 1); 
     } else { 
      return $result; 
     } 
    } 

} 

回答

1

你鴕鳥政策需要在你的第一個功能綁定任何參數,你需要做的是,在你的第二個功能,在執行準備好的語句權利之前。

編輯:順便說一句,您還可以調用execute一個數組,其中包含您的參數作爲鍵和您要發送的值。

+0

這是我做的。它工作得非常好。如果有需求,我會在一個答案中發佈我的代碼,但它非常符合沼氣標準的PHP。 – 2011-05-06 22:09:29

1

這個班級定義有太多的錯誤.. ehh。

它應該是這樣的:

class RepositoryException extends Exception{} 

interface iRepository 
{ 
    public function store($key , PDOStatement $statement); 
    public function fetch($key); 
} 

class StatementRepository implements iRepository{ 

    protected $_pool = array(); 

    public function store($key , PDOStatement $statement) 
    { 
     $this->_pool[ $key ] = $statement; 
    } 
    public function fetch($key) 
    { 
     if (!array_key_exists($key , $this->_pool)){ 
      throw new RepositoryException( 
       "Statement with name '$key' does not exist"); 
     } 

     return $this->_pool[ $key ]; 
    } 
} 

$repo = new StatementRepository; 

$foo = new Foo($repo); 
$bar = new Bar($repo); 

$db = new PDO('sqlite::memory:'); 
$statement = $db->prepare('SELECT .... '); 

$repo->store('bljum' , $statement); 

這種方式已經在構造函數中接受它實現了由名iRepository可以fetch報表對象中的所有對象。

你的課不應該有更多的責任,然後它需要。如果它用於存儲準備好的語句,那麼它應該與將參數綁定到它們並執行某些操作無關。

這裏是Foo類會做:

class Foo 
{ 
    protected $_repo = null; 

    public function __construct(iRepository $repo) 
    { 
     $this->_repo = $repo; 
    } 

    public function ergo($x , $y) 
    { 
     $statement = $this->_repo->fetch('bljum'); 
     //bind values 
     $statement->execute(); 
    } 

} 
相關問題