Registering Zend Database Adapter in Registry

2019-01-30 02:36发布

I am looking to register a reference to the main Database Adapter in the Registry during Bootstrapping so it can be used elsewhere in my site (specifically the Authorisation action).

I have implemented an ugly fix where i create a Database Table object and call the getAdapter() method on it and pass through that. However, this is a bad way of doing it and I would like it to be available via the registry.

Does anyone know how to do this? Any help or pointers in the right direction are appreciated!

Cheers Stuart

Ps. Im using Zend Framework 1.8.

9条回答
霸刀☆藐视天下
2楼-- · 2019-01-30 03:07

My 2 cents...

How to grab the default DB Adapter:

From Bootstrap:

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

From a Controller there are two methods:

<?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);
?>
查看更多
Ridiculous、
3楼-- · 2019-01-30 03:09

Here is what i do:

Inside the bootstrap:

define('CONFIG_FILE', '../config/general.ini');
define('APP_MODE', 'development');

Inside the Initializer:

 /**
 * 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');
    }
}

And finaly my config file looks like this:

[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 = 

Take a look at:

查看更多
闹够了就滚
4楼-- · 2019-01-30 03:09

I didn't want to use the registry to store an object that I should be able to access, so I did a little digging. It turns out that the bootstrap is registered as the front controller parameter "bootstrap", which is accessible from any of your controllers as explained in this manual page for Zend_Application.

So in your controller classes you can get the db adapter that has been defined in your ini file like this:

$bootstrap = $this->getInvokeArg('bootstrap');
$resource = $bootstrap->getPluginResource('db');
$db = $resource->getDbAdapter();
查看更多
登录 后发表回答