我可以从Propel连接中获取连接名称吗?

时间:2011-11-13 11:33:53

标签: php connection propel

我正在使用Propel 1.6.x,并希望能够从Propel Connection对象中检索连接名称。这是为了便于以单例方法存储对象,因此:

// 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 个答案:

答案 0 :(得分: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];
}

到目前为止似乎工作:)

相关问题