开发者

How to create a multi-key dictionary in PHP?

I use a static function to create a PDO object.

It accepts 2 params: a string and an object which contains the connection settings (dns, user, pass).

in order to prevent unnecessarily creating duplicate PDO connections with the same name, I tried to create a multi-key dictionary to cache the PDO object in.

Here is what I did:

include_once('IPDOSettings.php');

class PDOMa开发者_运维问答nager
{
    private static $connections; // array of connections

    public static function getConnection(IPDOSettings $settings, $connection_name = 'default')
    {
        $dictionary_key = array('name' => $connection_name, 'settings' => $settings);
        if(!self::$connections[$dictionary_key])
        {
            $DBH = new PDO($settings->getDNS(),$settings->getUser(),$settings->getPass());
            self::$connections[$dictionary_key] = $DBH;
        }
        return self::$connections[$dictionary_key];
    }

}

However after testing this I get this error Illegal offset type. After looking it up I find out that you cannot use objects or arrays as keys.

So is there anyway to do what I am trying to achieve?


Not really an answer to your question but do you expect PDOManager::getConnection() being called multiple times with the same $connection_name but different settings? Do you need to store the settings along with the db handle in your cache?

This problem wouldn´t even occur if you´d just store the connections by name:

    // my suggestion/idea: use $connection_name as key
    $dictionary_key = $connection_name; 

    if(!self::$connections[$dictionary_key])
    {
        $DBH = new PDO($settings->getDNS(),$settings->getUser(),$settings->getPass());
        self::$connections[$dictionary_key] = $DBH;
    }
    return self::$connections[$dictionary_key];

EDIT:

Well, if you cant just use $connection_name as a key, you could combine $connection_name and use spl_object_hash() in order to get your key:

    $dictionary_key = $connection_name . spl_object_hash($settings); 

This is much nicer then e. g. using serialize() to get a string representation of the $settings object.


Have a look at SplObjectStorage, it allows you to use an object as key.


I would do something like this:

$dictionary_key = $connection_name . $settings->toString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜