protected function _initDatabase()
{
$params = array(
'host' => '',
'username' => '',
'password' => '',
'dbname' => '',
);
$database = Zend_Db::factory('PDO_MYSQL', $params);
$database->getConnection();
return $database;
}
.
class App_Controller_Plugin_Test extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Http $request)
{
// how i get database?
}
}
You can always get a reference to the front controller:
$front = Zend_Controller_Front::getInstance();
From that you can get the bootstrap:
$bootstrap = $front->getParam("bootstrap");
From the bootstrap you can get bootstrap plugins:
if ($bootstrap->hasPluginResource("database")) {
$dbResource = $bootstrap->getPluginResource("database");
}
$db = $dbResource->getDatabase();
But that's a lot of extra plumbing!
Honestly, you'd be better off storing the database adapter object in the registry during your bootstrap:
protected function _initDatabase()
{
$params = array(
'host' => '',
'username' => '',
'password' => '',
'dbname' => '',
);
$database = Zend_Db::factory('PDO_MYSQL', $params);
$database->getConnection();
Zend_Registry::set("database", $database);
return $database;
}
Then you can get the database adapter anywhere:
Zend_Registry::get("database");
See also my answer to What is the “right” Way to Provide a Zend Application With a Database Handler
Too bad there's nothing like Zend_Controller_Action
's getInvokeArg("bootstrap")
in a plugin. You could always get the bootstrap reference through the front controller:
$db = Zend_Controller_Front::getInstance()->getParam("bootstrap")->getResource("database");
But what I usually do is
Zend_Registry::set('database', $database);
and then in your plugin:
try
{
$db = Zend_Registry::get('database');
}
catch (Zend_Exception $e)
{
// do stuff
}
Easier, and database can be retrieved pretty much anywhere in the application.
[I need to check this against some working code on another machine. I believe it's something like this...]
$db = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('db');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With