开发者

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 开发者_StackOverflowfunction 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');


$db = Zend_Db_Table::getDefaultAdapter();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜