2012-04-17 32 views
0

我在symfony 1.4项目中创建任务,我需要更新一些表格。在自定义任务中使用原则

我已经写了:

<?php 
class dataImportTask extends sfBaseTask 
{ 
    public function configure() 
    { 
    $this->namespace = 'data'; 
    $this->name  = 'import'; 

    $this->addOptions(array(
     new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'environment', 'dev'), 
    )); 
    } 

    public function execute($arguments = array(), $options = array()) 
    { 
    $databaseManager = new sfDatabaseManager(sfProjectConfiguration::getApplicationConfiguration('frontend', $options['env'], true)); 
    $connection = $databaseManager->getDatabase()->getConnection(); 
    } 
} 

(下面的例子中发现on symfony-project.org

但是,当我执行任务时,symfony说: “Database "default" does not exist.”。为什么这个任务不使用databases.yml中定义的dbname?

回答

4

这是使用任务时的常见问题。你有两个选择:

  • 命名在database.yml中
  • 您的教义连接default保持相同的名字在database.yml中,并在每个任务添加一个选项,以获取正确的数据库名称。

对于选项#2,你必须用你的数据库名称(在你database.yml的一个定义)增加一个选项,然后更改的方式getDatabase作品:

在database.yml中:

all: 
    doctrine: 
    class: sfDoctrineDatabase 

基于学说名称上方,添加选项中你的任务:

<?php 
class dataImportTask extends sfBaseTask 
{ 
    public function configure() 
    { 
    $this->namespace = 'data'; 
    $this->name  = 'import'; 

    $this->addOptions(array(
     new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'environment', 'dev'), 
     new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'), 
    )); 
    } 

    public function execute($arguments = array(), $options = array()) 
    { 
    $databaseManager = new sfDatabaseManager(sfProjectConfiguration::getApplicationConfiguration('frontend', $options['env'], true)); 
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection(); 
    } 
} 
+0

非常快,巨大的答案, 谢谢 ! – Manu 2012-04-17 15:44:43