2011-05-08 4 views
1

나는 일반적으로 여러 데이터베이스 중 하나를 선택하는 간단한 PHP/MySql 응용 프로그램을 가지고 있습니다 (고객마다 하나씩). 그러나 공통 데이터베이스에 액세스하는 유틸리티 기능을 자주 호출합니다.푸시/팝 현재 데이터베이스

코드 전체에 USE 절을 뿌리지 않으므로 각 유틸리티 기능의 시작 부분에 현재 데이터베이스를 밀어 넣고 마지막에 다시 팝업해야하는 것처럼 보입니다. 이것과 같은 것 (머리의 꼭대기에서, 그렇게 prolly는 일하지 않을 것이다. 그러나 생각을 줄 것이다).

function ConnectToDatabase($db) 
{ 
    global $current_database; 
    $current_database = $db; 
    odb_exec('USE ' . $db); // etc. Error handling omitted for clarity 
} 

function UtilityFunction() 
{ 
    odb_exec('USE common_db'); // etc. Error handling omitted for clarity 
    // do some work here 
    global $current_database; 
    ConnectToDatabase($current_database); 
} 

어쩌면 나는 PopCurrentDb 기능으로 global $current_database; ConnectToDatabase($current_database);를 결합하여이 예뻐 할 수 있지만, 당신은 그림을 얻는다.

이것은 PHP에서 더 잘 했습니까? MySql 솔루션이 있습니까 (나중에 ODBC 호환을 원하므로 PHP가 더 좋을 수도 있습니다). 다른 사람들은 어떻게합니까?


업데이트 : 결국 난 그냥 항상 완전히
예를 들어, 액세스 자격을하기로 결정 SELECT * from $database . '.' . $table

+2

처럼 보일 수 있습니다? :) – deceze

+1

db를 선택하려면 mysql_select_db를 입력하십시오. – Ibu

+0

+1 예, 두 번째 연결을 여는 것이 대안입니다. 하나만 가지고 있으면 간단하고 매우 복잡한 프로그램이 아닙니다. – Mawg

답변

4

왜 데이터베이스 관리자 클래스를 만들었습니까? 모든 엔티티에서 dbname/connection 저장 영역을 중앙 집중화하십시오. 그런 식으로 액세스하려면 명확한 API가 있어야하며 db를 이름으로 사용할 수 있습니다.

class MultiDb 
{ 

    /* 
    * Array of PDO DB objects or PDO DSN strings indexed by a connection/dbname name 
    * 
    * @var array 
    */ 
    protected $connections = array(); 

    /* 
    * The connection name currently in use 
    * @var string 
    */ 
    protected $currentConnection; 

    /* 
    * The Defualt connection name 
    * 
    * @var string 
    */ 
    protected $defaultConncetion; 

    /* 
    * @param array $connections Any array DSN or PDO objects 
    */ 
    public function __construct(array $connections); 

    public function getConnection($name); 

    // i would set this up to intelligently return registered connections 
    // if the argument matches one 
    public function __get($name) 

    // same with __set as with __get 
    public function __set($name, $value); 

    // proxy to the current connection automagically 
    // if current isnt set yet then use default so things 
    // running through this would actually result in 
    // call_user_func_array(array(PDO $object, $method), $args); 

    public function __call($method, $args); 

} 

그래서 사용 당신은 당신이 알고, 두 개의 데이터베이스 연결을 열 수 있습니다

// at the beginning of the app 

$db = new MultiDb(array(
    'util' => array('mysql:host=localhost;dbname=util;', 'user', 'pass'); 
    'default' => array('odbc:DSN=MYDSN;UID=user;PWD=pass;'); 
)); 


// some where else in the app we want to get some ids of some entities and then 
// we want to delete the associated logs in our shared utility DB 

// fetch the ids from the default db 

$ids = $db->default->query('SELECT c.name, c.id FROM some_table c') 
    ->fetchAll(PDO::FETCH_KEY_PAIR); 

// assume we have written a method 
// to help us create WHERE IN clauses and other things 
$in = $db->createQueryPart($ids, MultiDb::Q_WHERE_IN); 

// prepare our delete from the utility DB 
$stmt = $db->util->prepare(
    'DELETE FROM log_table WHERE id IN('.$in['placeholder'].')', 
    $in['params'] 
); 

// execute our deletion 
$stmt->execute(); 
+0

+1 감사합니다. 좋은 코드 – Mawg

1

푸시 (삽입) 및 팝 (제거 & 제거) 기능을 생성 하시겠습니까? 이 처리하려면 저장 프로 시저를 만들거나 PHP에서 여러 쿼리를 작성할 수 있습니다.

관련 문제