Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple DB connection class

How do you create multiple DB connections using Singleton pattern? Or maybe there's better approach, to share the same class but multiple connections?

like image 553
Deniss Kozlovs Avatar asked Dec 03 '25 22:12

Deniss Kozlovs


1 Answers

How about using a Factory pattern to return the same instance for each connection, e.g.

ConnectionFactory::getInstance(ConnectionFactory::DEVELOPMENT);

Returns a Connection instance for a connection to the development database.

Instantiation of the Connection should only be performed by the ConnectionFactory, which can keep references to those instances in a static array, keyed by the connection type. This avoid the singleton pattern, but ensures you only maintain a single instance of each Connection.

like image 178
David Grant Avatar answered Dec 05 '25 13:12

David Grant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!