2

I was advised to rewrite how I handle connection, as it is now, my class creates new connection on every instance of the object. How would I change it to share connection between multiple objects created with this class?

/**
* 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 Answers1

1

If you really need that, define your property as static:

private static $conn;

Of course, make sure that accessing to that will be done right (i.e. not via $this, but via self (or class name) since it will be no longer belong to instance)

That, however, isn't a good practice: if you want manage connections - manage how many times you'll instantiate your class.

Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • So if I do new Uesrs; once and use that throughout single php file, I will in essence have single connection, without rewriting anything, correct? –  Feb 10 '14 at 14:28
  • Yes, it will (but don't forget to initialize your connection in first usage, of cause) – Alma Do Feb 10 '14 at 14:29