With PHP what would be faster: multiple DB connection class instances or a singleton?

I am working a new PHP project that calls upon a records class to update the database. Currently every object or script that needs to do so makes a new instance of the object. In theory this could mean as many as six or seven instances per call.

The design currently calls for the object to connect to the database in the constructor method which would mean between 0 and 7 connections?

For the demo I will be using only MySQL but as it is all tucked away behind a single interface one imagines that it could easily be ported to other data stores (and probably will).

Given the nature of the project speed of response is the key optimisation point however with so many connections do I run the risk of overloading the system when demand is high and therefore slowing everything down anyway?

Is this a situation when it would simply be better (and faster overall) to use a singleton?

Or is there some way to have my cake and eat it?

Upvotes: 0

Views: 853

Answers (3)

wake-up-neo
wake-up-neo

Reputation: 814

Look at this solution. It uses singleton approach for each connection and handles multiple connections across multiple adapters (e.g. mysql, memcached etc.)

Upvotes: 0

4EACH
4EACH

Reputation: 2197

I can suggest you two solutions:

  1. Use stored procedure if you can, it will decrease # of Mysql connections, its more safety, and its cached.

  2. Use at first time Mysql connection and than save data into Redis or Memcached.

It intend to your queries and your needs.

Thanks

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157967

A connection to a database server takes time to connect and will consume memory. Also the number of connections a database server will accept at the same time is limited. That's why the number of connections should be kept as small as possible which means that only a single connection to the same database should be used.

Using just a single connection means not that you have to use the Singleton pattern. Simply create the connection object somewhere at the start of the script and pass it to components which will execute DB queries.

Upvotes: 3

Related Questions