Archive for June, 2012

Querying the database from a TWIG extension in Symfony 2

Posted in PHP, Symfony on June 1st, 2012 by Comments Off

Creating a TWIG extension in Symfony 2 is easy. Sometimes you need to execute database queries from a TWIG extension, but in order to do so, you have to tell Symfony to pass the Doctrine entity_manager as a parameter to the TWIG extension.

First, add a service record to your application config.yml file along with some configuration parameters.

app/config/config.yml

services:
    my.twig.extension:
        class: CodeRelic\SampleBundle\Extension\CodeRelicTwigExtension
        tags:
            -  { name: twig.extension }
        arguments:
            em: "@doctrine.orm.entity_manager"

The above service definition is quite self forward. It tells Symfony where your extension lives and what arguments to pass to it. The twig.extension tag also let’s Symfony know that this service needs to be loaded as a TWIG extension.

The next step is to create the extension. Create a folder called “Extension” inside your bundle. In this example, the file is created in:

src/CodeRelic/SampleBundle/Extension/CodeRelicTwigExtension.php

<?php
 
namespace CodeRelic\SampleBundle\Extension;
 
class CodeRelicTwigExtension extends \Twig_Extension
{
    private $em;
    private $conn;
 
    public function __construct(\Doctrine\ORM\EntityManager $em) {
        $this->em = $em;
        $this->conn = $em->getConnection();
    }
 
    public function getFunctions()
    {
        return array(
            'categories' => new \Twig_Function_Method($this, 'getCategories'),
        );
    }
 
    public function getCategories()
    {
        $sql = "SELECT * FROM categories ORDER BY name";
        return $this->conn->fetchAll($sql);
    }
 
    public function getName()
    {
        return 'code_relic_twig_extension';
    }
}

This is all you should have to do in order to get your TWIG extension working and to be able to use the database from it. In the above code sample, we have defined a TWIG function called “categories,” so in your TWIG layout files, you can now loop through all the categories in your database. See example below.

<ul>
{% for category in categories() %}
    <li>{{ category.name }}</li>
{% endfor %}
</ul>