Registering Zend Database Adapter in Registry

后端 未结 9 2012
温柔的废话
温柔的废话 2020-12-23 00:07

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

9条回答
  •  自闭症患者
    2020-12-23 00:43

    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:

    • Zend_Db::Factory()
    • Zend_Config_Ini
    • Zend_Registry

提交回复
热议问题