如何与对象的多个实例共享相同的连接?

时间:2014-02-10 14:05:14

标签: php oop

我被建议重写我如何处理连接,就像现在一样,我的类在对象的每个实例上创建新连接。如何更改它以共享使用此类创建的多个对象之间的连接?

/**
* This is Users class, deals with finding, updating, creating user
*/
class Users
{

    private $host   = DB_HOST;
    private $user   = DB_USERNAME;
    private $pass   = DB_PASSWORD;
    private $dbname = DB_NAME;

    private $conn;
    private $stmt;
    public  $error;

    function __construct()
    {
        $dsn = 'mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8';
        $options = array(
            PDO::ATTR_EMULATE_PREPARES  => false,
            PDO::ATTR_PERSISTENT        => true,
            PDO::ATTR_ERRMODE           => PDO::ERRMODE_EXCEPTION
        );
        try {
            $this->conn = new PDO($dsn,$this->user,$this->pass,$options);
        } catch (PDOException $e) {
            $this->error = $e->getMessage();
        }
    }

    private function mysql_execute_query($sql,$params)
    {
        $this->stmt = $this->conn->prepare($sql);
        $this->stmt->execute($params);
        return $this->stmt;
    }

    public function find_user_by_provider_uid($provider,$provider_uid)
    {
        $sql = 'SELECT * FROM users WHERE provider = :provider AND provider_uid = :provider_uid LIMIT 1';
        $params = array(
            ':provider'     => $provider,
            ':provider_uid' => $provider_uid
        );
        $result = $this->mysql_execute_query($sql,$params);
        return $result->fetch(PDO::FETCH_ASSOC);
    }
}

1 个答案:

答案 0 :(得分:1)

如果您确实需要,请将您的媒体资源定义为static

private static $conn;

当然,请确保访问权限(即不是通过$this,而是通过self(或类名),因为它将不再属于实例)

然而,这不是一个好习惯:如果你想管理连接 - 管理你实例化你的课程的次数。