Symfony: Executing queries after load fixtures

In this post we will see how to use symfony’s events to execute SQL queries after loading fixtures.

Sometimes we have the need to execute some SQL queries after we have loaded our fixtures, for instance, we need to do something specific for our RDBMS (Relational Database Management System) which is not supported by Doctrine nor Propel. Fortunately, symfony 1.4 has an excellent events system which allows us to connect the framework’s core and execute our own code when certain actions take place.

The below code snippet is an example of how we can execute some SQL queries manually after of doctrine:data-load:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
class ProjectConfiguration extends sfProjectConfiguration
{
    public function setup()
    {
        // ...
        $this->dispatcher->connect('command.post_command', array(
            $this, 'listenToCommandPostCommandEvent'
        ));
    }

    public function listenToCommandPostCommandEvent(sfEvent $event)
    {
        $invoker = $event->getSubject();
        if($invoker instanceof sfDoctrineDataLoadTask)
        {
            $conn = Doctrine_Manager::connection();
            $conn->exec(// ...);
        }
    }
}

Symfony 1.4 have a lot of events we can use to customize features. You can learn more about these events in the Symfony’s documentation.