PHP使用单个数据库对象连接Oracle DB - Singleton Pattern

时间:2014-12-01 12:15:48

标签: php oracle singleton

PHP脚本:

class db_singleton
{
    const ORACLE_HOST = "SOMEVALIDIP";
    const ORACLE_USER = "oracleuser";
    const ORACLE_PASS = "oraclepass";
    const ORACLE_DB = "SOMEVALIDIP/ORACLEDB";

    private static $instance; // stores the instance

    private function __construct() { } // block directly instantiating

    private function __clone() { } // block cloning of the object


        /*public static function getInstance() {

        if(!self::$instance) {
            // instance doesn't exist yet, so create it
            self::$instance = new self();
        }

        // return an instance of this class (Database)
        return self::$instance;
        }*/   

    public static function call()
    {
        // create the instance if it does not exist
        if(!isset(self::$instance))
        {
            // the ORACLE_* constants should be set to or
            //  replaced with your db connection details
            self::$instance = oci_connect(self::ORACLE_HOST, self::ORACLE_USER, self::ORACLE_PASS, self::ORACLE_DB);
            if(self::$instance->connect_error)
            {
                throw new Exception('Oracle connection failed: ' . self::$instance->connect_error);
            }
        }
        // return the instance
        return self::$instance;
    }
}

要进行查询,我写下代码:

$result = db_singleton::call()->query("SELECT * FROM some_valid_table"); 
print_r($result);exit;

上面给出了例外:

Fatal error: Call to a member function query() on a non-object 

不确定连接Oracle DB使用PHP Singleton Pattern

感谢。

2 个答案:

答案 0 :(得分:2)

oci_connect返回resource。您应该使用oci_函数系列从DB获取数据,例如:

oci_execute( 
  oci_parse( 
    db_singleton::call(), 'SELECT * FROM some_valid_table' 
  ) 
);

链接页面提供了更多示例。

答案 1 :(得分:0)

来自php.net

resource oci_connect ( string $username , string $password [, string $connection_string [, string $character_set [, int $session_mode ]]] )

一个例子:

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('username', 'password', 'localhost/XE');