gpt4 book ai didi

php - 如何在 Zend Framework 的 Controller 插件中获取引导资源

转载 作者:IT王子 更新时间:2023-10-29 00:01:05 25 4
gpt4 key购买 nike

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?

}
}

最佳答案

您始终可以获得对前端 Controller 的引用:

$front = Zend_Controller_Front::getInstance();

从那里你可以获得 Bootstrap :

$bootstrap = $front->getParam("bootstrap");

从 bootstrap 中你可以获得 bootstrap 插件:

if ($bootstrap->hasPluginResource("database")) {
$dbResource = $bootstrap->getPluginResource("database");
}
$db = $dbResource->getDatabase();

但这需要很多额外的管道!

老实说,您最好在引导过程中将数据库适配器对象存储在注册表中:

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;
}

然后你可以在任何地方获取数据库适配器:

Zend_Registry::get("database");

另请参阅我对 What is the “right” Way to Provide a Zend Application With a Database Handler 的回答

关于php - 如何在 Zend Framework 的 Controller 插件中获取引导资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2970548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com