我是 Cake 开发的新手。我面临的问题是在脚本本身中设置数据源。我的 database.php 是;
function __construct()
{
if(getenv('ENVIRONMENT') == 'staging') {
$this->default = $this->staging;
} else {
$this->default = $this->production;
}
}
所以,我根据网络服务器的环境设置来设置数据库。自然,php-cli 无法访问此变量。我最终要做的是创建一个 cakephp shell 任务。
class SelectEnvTask extends Shell {
public function execute()
{
App::Import('ConnectionManager', 'Model');
$configs = ConnectionManager::enumConnectionObjects();
if (!is_array($configs) || empty($configs)) {
$this->out('Error! No database configuration has been found.');
}
$connections = array_keys($configs);
if(!isset($this->args[0])) {
$this->out('Error! Please enter one of the environment settings as an argument: ' . implode('/', $connections) .
"\n\n" . 'eg. ./Console/cake *script_name* *environment*', 2);
exit(1);
}
if(!in_array($this->args[0], $connections)) {
$this->out($this->args[0] . ' environment could not be found!', 2);
exit(1);
}
//hacky solution until finding a better one
$models = App::objects('Model');
foreach($models as $model) {
ClassRegistry::init($model)->setDataSource($this->args[0]);
}
}
}
这可以正常工作,但是正如您在下面的任务中看到的,我获取了所有模型名称并更改了它们的数据库连接,这不是一个好习惯。我也不想在数据库类中设置更多变量,并希望在 shell/tasks 中处理这些变量。
有没有更优雅的方法来实现这一点?
谢谢,