Search code examples
symfony1task

How to access database from configure method of a symfony task


You can create a symfony "task" by extending sfBaseTask; see http://www.symfony-project.org/cookbook/1_1/en/tasks for more details.

However, I cannot see how to set up a database connection in the configure section. I want to do this so that I can have the detailedDescription property show some options that are only defined in the database.

What is the best way to do this?


Solution

  • If you check out the way symfony creates a custom Task Skeleton (./symfony generate:task yourTaskName), you would see code that looks like this inside the execute function:

    protected function execute([..])
    {
         $databaseManager = new sfDatabaseManager($this->configuration);
         $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
    [..]
    

    The problem with this code is that it uses the default configuration, but if you know what connection you want to open (check your database.yml or schema.yml to figure out the name) it should be really easy, with code that looks like this:

    protected function configure()
    {
             $databaseManager = new sfDatabaseManager(sfProjectConfiguration::getApplicationConfiguration('frontend'‌​, 'prod', true));
             $connection = $databaseManager->getDatabase("the_name_of_your_connection")->getConnection();  
    [..]
    

    Then you can access your models the usual way, e.g.:

        $myItem = Doctrine_Core::getTable('item')->find(14);
        echo $myItem->getId();