开发者

Making an Oracle DB connection from PHP without make duplicate connections

开发者 https://www.devze.com 2023-04-05 05:20 出处:网络
I currently make an Oracle connection like this: $c = oci_connect(\'username\', \'password\', \'host\');

I currently make an Oracle connection like this:

$c = oci_connect('username', 'password', 'host');

which I use my oci8 queries like this:

$s = oci_parse($this->c, $query);
oci_execute($s);

However, every time I want to query, I create a new c开发者_StackOverflowonnection i.e. I do $c = ... many times. This is a silly thing to do. What is the correct or best way to make a single Oracle connection and use that connection from anywhere in the program? I can make $c I global variables but global variables aren't nice.

Thanks very much :).


Maybe you should use oci_pconnect as it creates a persistent connection. php manual oci_pconnect

Another way would be to use the singleton pattern, which is discouraged because you cannot unit test it.


Couldn't you use a static variable, like this...

class DbHandler {
    private static $_mOciHandle;

    private function __construct() {}

    GetHandle ($u, $p, $dsn, $charset) {
        if (!isset(self::$_mOciHandle))
            self::$_mOciHandle = oci_connect ($u, $p, $dsn, $charset);
        return self::$_mOciHandle;
        }
}

It still renders your database handle (indirectly) global, but you only ever have one connection, and this way it's protected from "accidental" update.

0

精彩评论

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