zozo
zozo

Reputation: 8582

zend - connect to a database from a controller

I have the following setup for a game:

One database with all users, one database with users that didn't complete the tutorial. In the first database I have a flag that tells me if user "Gogu" completed the tutorial or not. If he didn't, I need to connect to the second database and get some data. After some research I found this: connecting to two different databases with Zend Framework.

The thing is that since only like 5% of the users will be in tutorial progress is no use to keep both connections so I only need to connect while in a controller, get what I need and close the connection.

Any idea how to do this?

Upvotes: 1

Views: 570

Answers (1)

Christian Burger
Christian Burger

Reputation: 675

You don't have to worry about 2 connections, because Zend_Db "lazy loads" the connection. From the ZF manual:

Creating an instance of an Adapter class does not immediately connect to the RDBMS server. The Adapter saves the connection parameters, and makes the actual connection on demand, the first time you need to execute a query. This ensures that creating an Adapter object is quick and inexpensive. You can create an instance of an Adapter even if you are not certain that you need to run any database queries during the current request your application is serving.

http://framework.zend.com/manual/en/zend.db.adapter.html#zend.db.adapter.connecting.getconnection

Just note that the method used in the accepted answer you referred calls $db->getConnection() from the bootstrap. This not recommended because it will defeat the purpose of lazy loading. You could also consider Zend_Application_Resource_Multidb, which is perhaps a more elegant approach:

http://framework.zend.com/manual/en/zend.application.available-resources.html#zend.application.available-resources.multidb

Upvotes: 3

Related Questions