Hi,
If you're creating a database abstraction class, is there any reason not to connect to the database in the constructor? I continually see examples of methods (like query($sql)) within the abstraction class checking to see if there's a database connection and creating it if it doesn't exist before they continue. Putting the connection into the constructor means you never need to check for the connection because if it wasn't there the object wouldn't have been instantiated from the class in the first place.
I was wondering if there's some reason not to connect to the database until the very second you need it.
So basically this:
class Database
{
protected $db;
public $dbname;
public $host;
public $user;
public $password;
public function __construct($host, $user, $password, $dbname)
{
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->dbname = $dbname;
$this->db = $this->connect(); // Any reason not to do this here?
}
public function connect()
{
$this->db = new mysqli($this->host, $this->user, $this->password, $this->dbname);
return $this->db;
}
}
Instead of this:
class Database
{
protected $db;
public $dbname;
public $host;
public $user;
public $password;
public function __construct($host, $user, $password, $dbname)
{
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->dbname = $dbname;
$this->db;
}
public function connect()
{
$this->db = new mysqli($this->host, $this->user, $this->password, $this->dbname);
return $this->db;
}
public function query($sql)
{
// Connect to database if not already connected
if( ! is_resource($this->db))
$this->connect();
// Rest of method....
}
}
Thanks!