【问题标题】:Override core Magento DB connection using environment variables使用环境变量覆盖核心 Magento DB 连接
【发布时间】:2014-06-06 22:57:45
【问题描述】:

我正在尝试使用加载到我的 Magento 应用程序中的环境变量来覆盖默认的数据库连接凭据。

我已经设法“几乎”使用 getenv('MY_CUSTOM_VAR') 让它工作,但是我正在尝试使用相同的方法来覆盖数据库凭据,因此这些敏感数据可以存储在 htaccess 中。

例如

# .htaccess file
 SetEnv DB_USERNAME root
 SetEnv DB_PASSWORD password123
 SetEnv DB_HOST localhost

我的 App.php(在 app/code/local/Mage/Core/Model/App.php - 来自核心池的副本)

// my function that overrides the core one
protected function _initBaseConfig()
{
    Varien_Profiler::start('mage::app::init::system_config');
    $this->_config->loadBase();

    /* Read DB connection config from environment variables */
    $connection = $this->_config->getNode('global/resources/default_setup/connection');
    $connection->setNode('host', getenv('DB_HOST'));
    $connection->setNode('username', getenv('DB_USERNAME'));
    $connection->setNode('password', getenv('DB_PASSWORD'));

    Varien_Profiler::stop('mage::app::init::system_config');
    return $this;
}

我希望刚刚创建的 $connection 成为站点范围内使用的默认全局数据库连接,这段代码似乎可以做到这一点,但如果我为 DB_HOST/DB_PASSWORD 等输入纯随机条目。它仍然连接到数据库表明它没有覆盖使用 Magento 设置配置的默认数据库设置。

关于如何让这个 $connection 覆盖并成为“全局”数据库连接的任何想法?

如果这个问题与我之前的问题相似,请提前致歉,原来的问题有点笼统,而这个问题更侧重于特定部分。

更新... 我在 app/etc 目录中打开了 local.xml 并将“默认设置”数据库连接设置为非活动状态(通过将活动节点值更改为 0),这正如预期的那样返回错误。看起来覆盖函数似乎不喜欢覆盖初始数据库连接..有什么想法吗?

【问题讨论】:

  • 我假设缓存已启用配置?如果是这样,您可能希望完全禁用所有缓存,正如您在 lib/Varien/Simplexml/Config.php 中找到的那样,在读取所有 XML 之后,它被构建为一个并缓存。 header("Content-Type: text/xml"); die(Mage::app()->getConfig()->getNode()->asXML());
  • 为什么?这个的使用场景是什么?

标签: php .htaccess magento database-connection


【解决方案1】:

对于 MySQL db,您可以执行以下操作:

  1. 复制文件 lib/Zend/Db/Adapter/Mysqli.php 到 app/code/local/Zend/Db/Adapter/Mysqli.php
  2. 打开app/code/local/Zend/Db/Adapter/Mysqli.php,找到_connect()函数。
  3. 在第 317 行附近的这个函数中,你会看到:

    $_isConnected = @mysqli_real_connect(
    $this->_connection,
    $this->_config['host'],
    $this->_config['username'],
    $this->_config['password'],
    $this->_config['dbname'],
    $端口
    );

  4. 重新定义参数:

    $this->_config['host'] = getenv('DB_HOST');
    $this->_config['username'] = getenv('DB_USERNAME');
    $this->_config['password'] = getenv('DB_PASSWORD');

    $_isConnected = @mysqli_real_connect(
    $this->_connection,
    $this->_config['host'],
    $this->_config['username'],
    $this->_config['password'],
    $this->_config['dbname'],
    $端口
    );

  5. 清除缓存并重新启动 MySQL。对于其他数据库,请检查 lib/Zend/Db/Adapter 文件夹中的文件(DB2.php、Oracle.php、Sqlsrv.php)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多