Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a bootstrap resource in a controller plugin in Zend Framework

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?

    }
}
like image 686
y2k Avatar asked Jun 03 '10 23:06

y2k


3 Answers

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

like image 173
Bill Karwin Avatar answered Nov 05 '22 16:11

Bill Karwin


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.

like image 6
typeoneerror Avatar answered Nov 05 '22 14:11

typeoneerror


[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');
like image 5
allnightgrocery Avatar answered Nov 05 '22 15:11

allnightgrocery