Reputation: 529
I have written a data class for handling MySQL queries and then all other classes such as login
, products
extend this class to make use of the database. As a result, each page load creates 2 or more DB connections due to something similar to the following:
$login, parent::__construct(); // check login via db
$products, parent::__construct(); // fetch products from db
Is there a way around this such as adding some code in the constructor to verify whether an existing DB connection has already been established?
A fellow developer I work with writes in procedural style and simply uses a single global $_db object
for all queries and, this seems a lot more efficient as it only creates 1 DB connection.
Upvotes: 2
Views: 802
Reputation: 529
Michael's example of creating a static class and how to use it helped resolve the problem.
https://stackoverflow.com/a/26981461/541091
Upvotes: 0
Reputation: 163232
For many smaller applications, I make my database instance global to the whole application, along with configuration and other application-wide classes, such as logging. This is not necessarily the preferred method, as it couples code to expect things named certain ways, and could possibly cause conflicts down the road. However, for small utility applications it is convenient.
For anything larger, I usually utilize my DB from an ORM anyway, so it becomes a non issue.
Upvotes: 3