I am using a small scale custom PHP MVC inspired framework and have reached the point where i have many queries on the site, each query is in its own xxxModel.php file, and each xxxModel.php file extends the database connection class.
The general structure is similar to this:
- PostsModel extends CoreModel.
- CoreModel extends DatabaseClass.
In DatabaseClass i am connecting to mysql using PDO like this:
public function __construct()
{
parent::__construct("mysql:host=".HOSTNAME.";dbname=".DB_DATABASE."",DB_USER,DB_PASS);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
Until this point it is all working well, as it should.
The only problem is that each time i instantiate a new model, it eventually creates a new database connection since each xxxModel.php file extends Model.php which extends the DatabaseClass.
This at times is causing a “max_user_connections” error, and just connects to the database many times, which seems inefficient.
My question is what is a better practice of connecting to the database, and how should this multiple connections be handled?
Is it ok to have multiple connections (to the same database) or is it better to have one connection (or a limited amount) and just reuse that connection object?
I have googled this but have found quite a few different answers and each answer claims that the other solution is “bad”, e.g., using a singleton database class.
The singleton database class is the most common answer i find, which basically says that if you are going to use the same connection for the whole system, connect to the database in a singleton class, and just use that same object throughout the system. But even in the answers that give the singleton approach as the solution - it is also said that its not a good approach, so i wonder what is?
Any thoughts on this would be great, thanks!