在注册表中注册Zend数据库适配器

37

我希望在引导过程中向注册表中注册主数据库适配器的引用,以便其他地方可以使用它(特别是授权操作)。

我已经实现了一个丑陋的解决方法,其中我创建了一个数据库表对象并调用其getAdapter()方法并通过它进行传递。但是,这是一种不好的做法,我希望它可以通过注册表提供。

有谁知道怎么做吗?任何帮助或指向正确方向的提示都将不胜感激!

我正在使用Zend Framework 1.8。


我遇到了同样的问题。文档提到要检索适配器实例:http://framework.zend.com/manual/en/zend.application.available-resources.html#zend.application.available-resources.db 但是这对我似乎不起作用。 - jamiei
我认为OP的意思是如何使用文档(http://framework.zend.com/manual/en/zend.application.available-resources.html#zend.application.available-resources.db)中提到的config/bootfile检索默认适配器设置的实例。 - jamiei
9个回答

71
如果您使用Zend Framework 1.8+并使用命令行工具创建了您的项目,那么只需在application.ini配置文件中注册您的数据库设置即可。
resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "your.database.host"
resources.db.params.dbname = "database_name"
resources.db.params.username = "username"
resources.db.params.password = "password"
resources.db.isDefaultTableAdapter = true
如果你的数据库设置前面带有resources.db,那么你甚至不需要在Bootstrap.php文件中做任何事情,因为它会自动为你完成。此外,通过将isDefaultTableAdapter设置为true,你可以在应用程序的任何地方获得数据库适配器的实例。
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

10
谢谢你...为什么ZF文档一直要引用一些奇怪的SQLite内存设置来参考$dbAdapter.. getDefaultAdapter()应该是在整个文档中始终引用当前$dbAdapter的默认方式。天啊,SO从未让我失望过。 - Mahdi.Montgomery

13
感谢回复。我决定更改接受的答案并发布最终使用的解决方案 - 最终非常简单!!
这基本上是基于Dcaunt的评论...
在bootstrap类中..
protected function _initDb()
{
    $resource = $bootstrap->getPluginResource('db');

    $db = $resource->getDbAdapter();

    Zend_Registry::set("db", $db);
}

然后在其他地方访问它,使用...

$dbAdapter = Zend_Registry::get("db");

感谢帮助,希望能对其他人有所帮助。


// 在引导类中,正确的资源访问方式为: $resource = $this->getPluginResource('db'); - A. M.
1
我已经添加了我的答案,这使得它比这更容易! - Andrew

7

你错过了最好的东西 :)

如果你使用Zend_Db_Table模型(你应该这样做)等,那么你可以设置一个默认的适配器 - 这样当你实例化一个模型时,数据库连接就被处理了 - 这样你不需要真正保存它在注册表中或在通过模型运行查询之前打扰连接。

如果需要,我会将其保存在注册表中以备后用,但我可能会删除此功能。

protected function _initDB()
{
    // Check that the config contains the correct database array.
    if ($this->_config->db) {

        // Instantiate the DB factory
        $dbAdapter = Zend_Db::factory($this->_config->db);

        // Set the DB Table default adaptor for auto connection in the models
        Zend_Db_Table::setDefaultAdapter($dbAdapter);

        // Add the DB Adaptor to the registry if we need to call it outside of the modules.
        Zend_Registry::set('dbAdapter', $dbAdapter);
    }
}

谢谢。我稍微修改了一下就使用了。 - Rajan Rawal

4

我个人的看法...

如何获取默认的数据库适配器:

从Bootstrap中获取:

<?php    
$dbResource = $this->getPluginResource('db');
db = $dbResource->getDbAdapter();
var_dump($db);
?>

从控制器中有两种方法:

<?php
// Method 1
$bootstrap = $this->getInvokeArg('bootstrap');
$dbResource = $bootstrap->getPluginResource('db');
$dbAdapter = $dbResource->getDbAdapter();
var_dump($dbAdapter);

// Method 2
$dbAdapter = Zend_Db_Table::getDefaultAdapter();
var_dump($dbAdapter);
?>

1

我不想使用注册表来存储我应该能够访问的对象,所以我进行了一些调查。结果发现引导程序被注册为前端控制器参数“bootstrap”,可以从任何控制器中访问,如Zend_Application的手册页面中所解释的那样。

因此,在您的控制器类中,您可以像这样获取已在ini文件中定义的db适配器:

$bootstrap = $this->getInvokeArg('bootstrap');
$resource = $bootstrap->getPluginResource('db');
$db = $resource->getDbAdapter();

1

请查看Zend文档: 15.5.3.3. 在注册表中存储数据库适配器

http://framework.zend.com/manual/en/zend.db.table.html

$db = Zend_Db::factory('PDO_MYSQL', $options);
Zend_Registry::set('my_db', $db);

// Later...

$table = new Bugs(array('db' => 'my_db'));

你是在寻找类似这样的东西吗?

编辑:
如果要从 ini 文件中加载配置,请使用:
parse_ini_file($inifile)

;configuration.ini
host = 127.0.0.1
user = username
password = blabla

;yourfile.php
$options = parse_ini_file('configuration.ini');

$db = Zend_Db::factory('PDO_MYSQL', $options);

这是我在文档和其他网站上看到的,但是$ options变量可能包含用户名、密码、dbName等等。但在我的情况下,这些存储在Application.ini文件中。有没有一种方法可以使用此文件来填充选项?感谢您的快速回复! - Stuart
不是的。这是代码重复。他的意思是如何在不再读取配置文件的情况下检索默认适配器的实例(这是在引导类中自动完成的)。 - jamiei
虽然我可能对OP的意图非常错误!不过关于配置文件解析的回答很好。 - jamiei
非常感谢Silfverstrom的帮助! - Stuart
你正在重新发明轮子 - application.ini 已经在标准的 ZF 设置中解析了。我还将其设置推送到引导函数中的 zend_registry 中。无论如何,查看 @Andrew 的回复以获得一个好的解决方案。 - Tomasz Struczyński

1

我在我的引导程序中有一个方法来将适配器添加到注册表中。虽然我更喜欢一个更简洁的解决方案,但它确实有效:

protected function _initRegistry(){

    $this->bootstrap('db');
    $db = $this->getResource('db');

    $db->setFetchMode(Zend_Db::FETCH_OBJ);

    Zend_Registry::set('db', $db);
}

1
这是我所做的内容:
在bootstrap中:
define('CONFIG_FILE', '../config/general.ini');
define('APP_MODE', 'development');

初始化器内部:

 /**
 * Initialize data bases
 * 
 * @return void
 */
public function initDb ()
{
    $options = Zend_Registry::get('conf');
    $db = Zend_Db::factory($options->database);
    $db->query(new Zend_Db_Expr('SET NAMES utf8'));
    Zend_Registry::set('db', $db);
}

public function initConfig ()
{
    if (file_exists(CONFIG_FILE) && is_readable(CONFIG_FILE)) {
        $conf = new Zend_Config_Ini(CONFIG_FILE, APP_MODE);
        Zend_Registry::set('conf', $conf);
    } else {
        throw new Zend_Config_Exception('Unable to load config file');
    }
}

最终我的配置文件看起来像这样:

[production]
database.adapter         = pdo_Mysql
database.params.host     = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname   = dbname

; Overloaded configuration from production

[development : production]
database.params.host     = localhost
database.params.username = root
database.params.password = 

请看一下:


1
这不是正确的做事方式!在Bootstrap中自己加载配置并不必要,Zend_Application会自动完成这个过程。此外,它还有一个用于初始化数据库的资源。只需按照http://framework.zend.com/manual/en/zend.application.available-resources.html#zend.application.available-resources.db中的说明,在应用程序ini文件中指定数据库,数据库就会被自动初始化。 - David Snabel-Caunt

1
如果您正在使用Zend Framework 1.8,只需在您的控制器/动作中执行以下操作即可:
class CreateorderController extends Zend_Controller_Action
{
    public function testAction()
    {
        //more code
        $users_obj = new Default_Model_Users(); //this would load the model using the Default namespace
        //more code
    }
}

我的Defaul_Model_Users类看起来会像这样:

<?php
/**
 * application/models/Users.php
 */
class Default_Model_Users extends Zend_Db_Table
{
    protected $_table;

    public function getTable()
    {
        if(null === $this->_table) {
            $this->_table = new Default_Model_DbTable_Users();
        }
        return $this->_table;
    }

    public function fetchAll()
    {
        $result = $this->getTable()->fetchAll();

        return $result;
    }
}

与数据库表“交互”的模型部分位于DbTable目录中,其代码如下:

<?php
/**
 * application/models/DbTable/Users.php
 */
class Default_Model_DbTable_Users extends Zend_Db_Table_Abstract
{
    /** Table name */
    protected $_name = 'users';

    public function init()
    {
        $this->_db->setFetchMode(Zend_Db::FETCH_OBJ);
    }
}

那么我将拥有由Zend框架生成的相同application.ini,其中包含这个小修改:

resources.db.adapter               = "PDO_MYSQL"
resources.db.params.host           = "localhost"
resources.db.params.dbname         = "mydb"
resources.db.params.username       = "root"
resources.db.params.password       = "password"

这就是我做到的,而不必改变bootstrap文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接