我正在尝试使用加载到我的 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 覆盖并成为“全局”数据库连接有什么想法吗?
P.S 如果这个问题与我之前的问题相似,请提前致歉,原来的问题有点笼统,而这个问题更侧重于特定部分。
更新... 我已经打开 app/etc 目录中的 local.xml 并将“默认设置”数据库连接设置为非事件状态(通过将事件节点值更改为 0),这正如预期的那样返回错误。看起来覆盖函数似乎不喜欢覆盖初始数据库连接..有什么想法吗?
最佳答案
对于 MySQL 数据库,您可以执行以下操作:
- 将文件 lib/Zend/Db/Adapter/Mysqli.php 复制到 app/code/local/Zend/Db/Adapter/Mysqli.php
- 打开 app/code/local/Zend/Db/Adapter/Mysqli.php 并找到 _connect() 函数。
在第 317 行附近的这个函数中,您将看到:
$_isConnected = @mysqli_real_connect(
$this->_connection,
$this->_config['host'],
$this->_config['用户名'],
$this->_config['密码'],
$this->_config['dbname'],
$端口
);重新定义参数:
$this->_config['host'] = getenv('DB_HOST');
$this->_config['用户名'] = getenv('DB_USERNAME');
$this->_config['密码'] = getenv('DB_PASSWORD');$_isConnected = @mysqli_real_connect(
$this->_connection,
$this->_config['host'],
$this->_config['用户名'],
$this->_config['密码'],
$this->_config['dbname'],
$端口
);清除缓存并重新启动 MySQL。对于其他数据库,检查 lib/Zend/Db/Adapter 文件夹中的文件(DB2.php、Oracle.php、Sqlsrv.php)。
关于php - 使用环境变量覆盖核心 Magento DB 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23221776/