2011-11-13 70 views
1

我正在使用Propel 1.6.x,並希望能夠從Propel Connection對象中檢索連接名稱。這是爲了便於對象的存儲在一個單獨的方法,即:我可以從Propel連接獲取連接名稱嗎?

// If this is called twice with different connections, 
// the second one will be wrong 
protected function getHashProvider(PropelPDO $con) 
{ 
    static $hashProvider; 

    // Would like to use something like $con->getName() to 
    // store each instantiation in a static array... 
    if (!$hashProvider) 
    { 
     $hashProvider = Meshing_Utils::getPaths()->getHashProvider($con); 
    } 

    return $hashProvider; 
} 

由於連接目的是通過提供一個連接名(或接受默認名稱)我還以爲這個實例將被存儲在對象中。但通過代碼的粗略觀察似乎表明它只用於查找連接細節,而不是自己存儲。

有沒有我錯過了,或者我應該提交它作爲Propel2的建議? :)

回答

1

對,我發現在Propel內部,Propel::getConnection()根本沒有將名稱傳遞給PropelPDO類,所以它不可能包含我需要的東西。以下是我如何解決這個限制的想法。

我已經把那個連接需要有一個字符串標識的觀點,所以首先我創建了一個新的類來包裝的連接:

class Meshing_Database_Connection extends PropelPDO 
{ 
    protected $classId; 

    public function __construct($dsn, $username = null, $password = null, $driver_options = array()) 
    { 
     parent::__construct($dsn, $username, $password, $driver_options); 
     $this->classId = md5(
      $dsn . ',' . $username . ',' . $password . ',' . implode(',', $driver_options) 
     ); 
    } 

    public function __toString() 
    { 
     return $this->classId; 
    } 
} 

這給每一個連接字符串表示(使用它,我在運行時XML中添加了一個'classname'鍵)。接下來,我解決了單,於是:

protected function getHashProvider(Meshing_Database_Connection $con) 
{ 
    static $hashProviders = array(); 

    $key = (string) $con; 
    if (!array_key_exists($key, $hashProviders)) 
    { 
     $hashProviders[$key] = Meshing_Utils::getPaths()->getHashProvider($con); 
    } 

    return $hashProviders[$key]; 
} 

似乎工作至今:)

相關問題