2009-09-24 14 views
7

Chciałbym przedłużyć moje tabele w przypadku, gdy potrzebuję zainstalować aplikację na hoście z tylko jedną bazą danych. Zastanawiam się, czy istnieje prosty sposób pracy z prefiksami tabeli przy użyciu klasy PDO?PDO - Praca z prefiksami tabel

W tej chwili muszę nadpisać każdą metodę w mojej własnej owiniętej bazie danych, zastąpić% p prefiksem i wywołać metodę super. Działa, ale nie jest ładna!

Odpowiedz

9

Rozszerzenie klasy PDO jest prawdopodobnie najlepszą opcją.

class MyPDO extends PDO 
{ 
    protected $_table_prefix; 
    protected $_table_suffix; 

    public function __construct($dsn, $user = null, $password = null, $driver_options = array(), $prefix = null, $suffix = null) 
    { 
     $this->_table_prefix = $prefix; 
     $this->_table_suffix = $suffix; 
     parent::__construct($dsn, $user, $password, $driver_options); 
    } 

    public function exec($statement) 
    { 
     $statement = $this->_tablePrefixSuffix($statement); 
     return parent::exec($statement); 
    } 

    public function prepare($statement, $driver_options = array()) 
    { 
     $statement = $this->_tablePrefixSuffix($statement); 
     return parent::prepare($statement, $driver_options); 
    } 

    public function query($statement) 
    { 
     $statement = $this->_tablePrefixSuffix($statement); 
     $args  = func_get_args(); 

     if (count($args) > 1) { 
      return call_user_func_array(array($this, 'parent::query'), $args); 
     } else { 
      return parent::query($statement); 
     } 
    } 

    protected function _tablePrefixSuffix($statement) 
    { 
     return sprintf($statement, $this->_table_prefix, $this->_table_suffix); 
    } 
} 
+0

hi jest to tylko mnie czy na funkcji/metody '_tablePrefixSuffix' ostatni bit' $ this_table_suffix' jest to przypuszczać, aby być '$ this -> _ table_suffix'? – Val

+0

Nie jestem pewien, jak można to uznać za działający przykład, ponieważ 'sprintf' oczekuje ciągów formatujących ze specjalnymi kotwicami, ale argument' $ instrukcja' jest zwykłym łańcuchem, który po prostu zostaje zignorowany i zwrócony w niezmieniony sposób. –

+0

Ok, wymyśliłem to. Po prostu podajesz nazwę tabeli z kotwicami: '$ table ="% 1 \ $ s {$ table}% 2 \ $ s "' –