Is it a good idea to instantiate the db connection in a parent class then its children classes can inherit by it?
For instance, this is my core model,
class CoreModel
{
protected $connection;
public function __construct()
{
// Construct database connection data.
$this->connection = new Database(DSN,DB_USER,DB_PASS);
$this->connection->connect();
}
}
then I have these classes that extend from CoreModel
,
class Article extends CoreModel
{
public function __construct()
{
parent::__construct();
}
}
class Image extends CoreModel
{
public function __construct()
{
parent::__construct();
}
}
class Controller extends CoreModel
{
public function __construct()
{
parent::__construct();
}
}
Does it cause the db connection to be made endless times? so that would be 3 db connections in my case above?
If this is a bad idea, what is the base way to instantiate the db connection just once so that all the classes can depend on it?
EDIT:
$connection = new Database(DSN,DB_USER,DB_PASS);
$connection->connect();
$controller = new Controller($connection);
$article = new Article($connection);
class Article {
protected $connection;
public function __construct(Database $connection) {
$this->connection = $connection;
}
}