1

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 connection 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 :).

5
  • "global variables aren't nice" Why? Commented Sep 14, 2011 at 6:07
  • I don't want to start the global variables debate! They can be changed from anywhere (because they're global) so it's sometimes hard to figure out where they are being changed. Quick Google search revealed this: c2.com/cgi/wiki?GlobalVariablesAreBad Commented Sep 14, 2011 at 6:09
  • I have no intention of starting a debate. I am just throwing that out there because a lot of people have preconceived ideas like X is bad without really understanding why it's bad. In reality, what you can or can't do depends on how your code looks like. Sometimes a global variable may be the only option. Commented Sep 14, 2011 at 6:10
  • So would you consider this to be a case where global variables are a good solution? I used them to solve this problem in a previous problem but I wondered whether there was an alternative? Commented Sep 14, 2011 at 6:16
  • I am saying it depends on how your code is structured. Without looking at the rest of your code, it is hard to tell. Commented Sep 14, 2011 at 6:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.