Learn how to establish a database connection with Symfony 1.4 within a Task (Console Command).

There are a lot of ways to use the symfony commands. One of useful things that you can do is to automatize tasks related to the database of your project or even creating helper methods to clear tables etc in development mode. If you are working with Symfony 1.4, we'll explain you quickly how to access the database within a Task or Console Command of Symfony easily.

Retrieve a database connection 

As you may know, you can define multiple database connections on the ./proyect/config/databases.yml file. In this file, you can define a connection in the following way:

# You can find more information about this file on the symfony website:
# http://www.symfony-project.org/reference/1_4/en/07-Databases

all:
  doctrine:
    class: sfDoctrineDatabase
    param:
      dsn:      mysql:host=localhost;dbname=my_database
      username: root
      password: password

As you can see, in this example we have a simple connection named doctrine with the given configuration. So in our code to retrieve the connection, we'll use the named doctrine connection. Of your interest is however, a very simple helper method that you can add to your Task Class to retrieve the default connection:

<?php

/**
 * This method creates a connection to the default database of your application with Doctrine.
 * 
 * @return type
 */
private function getDefaultDatabaseConnection()
{
    $databaseManager = new sfDatabaseManager(sfProjectConfiguration::getApplicationConfiguration($application = "frontend", $env = "prod", $debug = true));
    
    // Get some connection stablished on the databases.yml file
    $databaseConnection = "doctrine";
    
    $databaseManager->getDatabase($databaseConnection)->getConnection();  
    
    return Doctrine_Manager::getInstance()->getCurrentConnection();
}

The getDefaultDatabaseConnection will return the defined doctrine connection on your databases.yml file, however you can change the name if it's other.

Task example

The following test task shows a basic example of the execution of the php symfony test-command:demo defined by the following class, where you will be able to use the database connection in the execute function:

<?php

// ./proyect/lib/task/TestCommandTask.class.php

/**
 * Example of Symfony 1.4 to get access to the database within a console command (task).
 * 
 * @author Carlos Delgado <[email protected]>
 */
class TestCommandTask extends sfBaseTask {

    public function configure()
    {
        $this->namespace = 'test-command';
        $this->name = 'demo';
        $this->briefDescription = 'This command does something';
        $this->detailedDescription = <<<EOF
Description of this command.
EOF;
    }
    
    /**
     * This method creates a connection to the default database of your application with Doctrine.
     * 
     * @return type
     */
    private function getDefaultDatabaseConnection()
    {
        $databaseManager = new sfDatabaseManager(sfProjectConfiguration::getApplicationConfiguration($application = "frontend", $env = "prod", $debug = true));
        
        // Get some connection defined on the databases.yml file
        $databaseConnection = "doctrine";
        
        $databaseManager->getDatabase($databaseConnection)->getConnection();  
        
        return Doctrine_Manager::getInstance()->getCurrentConnection();
    }
    
    /**
     * Action of the command.
     * 
     * @param type $arguments
     * @param type $options
     */
    public function execute($arguments = array(), $options = array()) {
        
        // Request access to database
        $conn = $this->getDefaultDatabaseConnection();
        
        // Now here you are able to execute queries in the way you want, or access tables with Doctrine e.g
        // $item = Doctrine_Core::getTable('items')->find(1);
        // $conn->execute("TRUNCATE `table_name`");
    }
}

Note that you can run either plain queries or using the doctrine model as well.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors