这个想法是,您的 Bootstrap 读取配置文件,并声明配置条目来描述您想要创建的数据库适配器:
[bootstrap]
resources.db.adapter = Pdo_Mysql
resources.db.params.dbname = "mydatabase"
resources.db.params.username = "webuser"
resources.db.params.password = "XXXX"
resources.db.isDefaultTableAdapter = true
如果您按照正确的约定使用配置键,这会自动向 Bootstrap 基类发出信号以创建并初始化Zend_Application_Resource_Db
对象,并将其存储在引导资源注册表 http://framework.zend.com/manual/en/zend.application.theory-of-operation.html#zend.application.theory-of-operation.bootstrap.registry.
稍后在您的控制器中,您可以访问资源注册表。note:经过更多测试后,我编辑了这段代码。
class SomeController extends Zend_Controller_Action
{
public function init()
{
$bootstrap = $this->getInvokeArg("bootstrap");
if ($bootstrap->hasPluginResource("db")) {
$dbResource = $bootstrap->getPluginResource("db");
$db = $dbResource->getDbAdapter();
}
}
}
或者,您可以在 Bootstrap 类中编写自定义 init 方法,以将对象保存在默认的 Zend_Registry 中:
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDb()
{
if ($this->hasPluginResource("db")) {
$dbResource = $this->getPluginResource("db");
$db = $dbResource->getDbAdapter();
Zend_Registry::set("db", $db);
}
}
}
现在,您可以一步而不是三步访问您的数据库对象:
class SomeController extends Zend_Controller_Action
{
public function init()
{
$db = Zend_Registry::get("db");
}
}
就我个人而言,我会使用第二种技术,因为这样我只需在引导程序中访问资源注册表一次。在第一个示例中,我必须将相同的代码块复制到我的所有控制器。