Tom*_*avo 6 php doctrine symfony-1.4 doctrine-1.2
(有关更好的问题,请参阅下面的编辑)如何在symfony1.4任务中使用通用Doctrine_Query::create()创建查询来控制选择哪个连接(来自database.yml中的右侧环境部分)?
我正在使用看起来像这样的database.yml:
prod:
doctrine:
class: sfDoctrineDatabase
param:
dsn: mysql://some:pass@domain:port/database
log:
class: sfDoctrineDatabase
param:
dsn: mysql://some:pass@domain:port/database
auth:
class: sfDoctrineDatabase
param:
dsn: mysql://some:pass@domain:port/database
dev:
doctrine:
class: sfDoctrineDatabase
param:
dsn: mysql://some:otherpass@domain:port/database
log:
class: sfDoctrineDatabase
param:
dsn: mysql://some:otherpass@domain:port/database
auth:
class: sfDoctrineDatabase
param:
dsn: mysql://some:otherpass@domain:port/database
Run Code Online (Sandbox Code Playgroud)
我希望能够在调用类似以下内容时控制使用哪个数据库定义:
$query = Doctrine_Query::create()
->select('*')
->from('Products p')
->where('p.id = ?', $productID)
->limit(1);
$OfpFlPr = $query->execute()->getFirst();
Run Code Online (Sandbox Code Playgroud)
目前我无法像这样设置连接$query = Doctrine_Query::create($conn);.
任何帮助将不胜感激!
编辑:
我在使用的软件中有很多代码Doctrine_Query::create()(没有连接参数).它似乎通过Web请求选择了正确的环境和连接.但是我无法弄清楚它是如何做到这一点的,所以我可以使我的CLI命令以相同的方式工作(它们目前没有选择正确的连接和环境).这就是为什么我需要知道如何控制"自动"使用哪个连接(默认选中).
题:
所以我想我的结论是:
如何控制Doctrine_Query::create()在代码作为symfony CLI命令执行时使用的较低级代码中默认选择的连接?
使用干净创建的任务进行一些深度调试后,我终于找到了罪魁祸首。Symfony 1.4 似乎configure在实际运行预期任务之前运行任务目录中每个任务的方法。
不幸的是,一些不知情的恶作剧者(前同事*)将一些硬编码的上下文初始化包含到这些方法之一中,如下所示:
// inside a task
protected function configure() {
// context was initialized
$configuration = ProjectConfiguration::getApplicationConfiguration('app_name', 'prod', true);
$context = sfContext::createInstance($configuration);
// so the following was available in the configure method
$save_path = sfConfig::get('sf_app_config_dir');
// rest of configure method implementation
// ...
}
Run Code Online (Sandbox Code Playgroud)
这搞乱了除生产环境(幸运的是)之外的所有其他环境中所有 cronjobs 的数据库设置。
我设法通过做这样的事情来解决这个问题:
protected function configure() {
$configuration = ProjectConfiguration::getApplicationConfiguration('app_name', 'prod', true);
// removed the context creation
$configuration->activate(); // this makes the sfConfig::get() work
$save_path = sfConfig::get('sf_app_config_dir');
// rest of configure method implementation
// ...
}
Run Code Online (Sandbox Code Playgroud)
我还发现,在控制使用哪个数据库连接时,Doctrine_Query::create()您可以通过在更高级别的函数上使用类似的东西来进行一些控制:
// for making sure the 'auth' database settings are used as a default
Doctrine_Manager::getInstance()->setCurrentConnection('auth');
Run Code Online (Sandbox Code Playgroud)
然而,这对使用什么“环境部分”来为数据库选择正确的配置/DSN 没有任何影响。这是通过执行以下操作来完成的:
// somewhere in the execute method
$env = 'dev'; // the environment section name;
$configuration = ProjectConfiguration::getApplicationConfiguration('app_name', $env, true);
$context = sfContext::createInstance($configuration);
Run Code Online (Sandbox Code Playgroud)
正如Alex Blex和Marek的答案中也正确暗示的那样。按照他们的建议,使用任务“选项”使其支持多个环境是有意义的。
*:我的前同事,我很难对他生气,因为这个问题不太可能且违反直觉;)