Zend Framework | Sharing DB-connection between Controllers

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Behzad
Forum Commoner
Posts: 28
Joined: Mon Jul 09, 2007 3:24 pm
Location: Tehran, Iran
Contact:

Zend Framework | Sharing DB-connection between Controllers

Post by Behzad »

Hi,

I'm just learning how to develop web applications using Zend Framework.

In a procedural PHP program, I usually establish the DB connection in prepend.inc.php.
Other scripts, have a include statement which enables them to use this connection,
and since the program runs from top to down, everything goes fine.

But I've troubles with ZF, I wonder how can I share a DB-connection between different Controllers
in Zend Framework? There are View and Controller for Model-View-Controller in ZF.
But where's the Model?
Begby
Forum Regular
Posts: 575
Joined: Wed Dec 13, 2006 10:28 am

Post by Begby »

The model is up to you to create. Zend includes some database object stuff, so on simpler apps that will be your model.

As for passing a connection around, you will want to use the registry. You can create a Zend_DB object then put it in the registry in your bootstrap. With Zend_DB a connection is really not made until you first connect to the database, so putting it in your bootstrap is ok.

You can then access the registry from anywhere in your controllers via a static call to Zend_Registry, or injecting it into your controller using setParam() and then using getInvokeArg in your base action controller to retrieve it.
Behzad
Forum Commoner
Posts: 28
Joined: Mon Jul 09, 2007 3:24 pm
Location: Tehran, Iran
Contact:

Post by Behzad »

How about this approach:

In your bootstrap do:

Code: Select all

$database = Zend_Db::factory($adapter, $config);
Zend_Db_Table::setDefaultAdapter($database);
Then in your models you can do:

Code: Select all

$db = $this->getAdapter();
Thanks to Jack Sleight.
Post Reply