Global Variables in Twig with Silex

Recently I assigned my user object to a template in my UserController. The moment I did this i realised I should assign this globally instead of reassigning it to each view. In my set-up, all my Controllers extend my CoreController class. It’s a place where I just put up some proxies that do a lot of general stuff so that my UserController (or other controllers) won’t be cluttered.

I’ve added my silex-base git repository to github, feel free to give me feedback on how my project structure looks. This repository can be installed using Composer and gives you the basic stuff you’ll need in an application. It used the Symfony Security component for registering and logging users in. Plus bonus points for twitter bootstrap.

I’ve added the filters class from my previous post (Extending Twig template engine with Silex) and a mysql dump for users and logging.  The project structure looks like this and links to the Github repository:

Silex-base Structure

Now, back to the global variable issue|bug|feature:
Because of my CoreController which has methods like getTwig() and getUser() I could easily do something like this:

    /**
     * @return \Twig_Environment
     */
    protected function getTwig() {
        // add globals
        $this->app['twig']->addGlobal('user', $this->getUser());
        return $this->app['twig'];
    }

    /**
     * @return User|Null|string
     */
    protected function getUser() {
        if(is_null($this->getSecurity()->getToken())) {
            return null;
        }

        return $this->getSecurity()->getToken()->getUser();
    }

    /**
     * @return SecurityContext
     */
    protected function getSecurity() {
        return $this->app['security'];
    }

Great, I can now use my $user object in any template. Next up is getting phpunit working within Silex.
Any hints and tips on my project structure are greatly appreciated.

Advertisements

Extending Twig template engine with Silex

In my Silex project I’m currently using the Twig template engine. It’s a truly great template compiler. But it’s so much more than that. Just a copy paste from the Twig website:

  • Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.
  • Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.
  • Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.

For me, it took me some time to get used to this way of using PHP and templates, but the Twig project is greatly documented. Guaranteed solutions can be found on their documentation pages.

I wanted to extend Twig to use my custom classes and methods. I have a web application with registered users who have an email address. I want to show their gravatar as distinct users in my layout.
I don’t want to create HTML code from within my controllers, but I want something like this:

   <div class="users">
      {% for user in users %}
         <img title="{{ user.name }}" alt="{{ user.name }}" src="{{ user.email|gravatar }}" />
      {% endfor %}
   </div>

First of, we need to create a class where we will put our filters which extends \Twig_Extension. This class can be stored anywhere, just make sure your namespace can be used in your bootstrap file. This could look something like this:

Filter class which extends \Twig_Extension
Filter class which extends \Twig_Extension

We need to overwrite the abstract methods getFilters which will need to return all your filters you want to use. (As stated in the abstract class \Twig_Extension: Returns a list of filters to add to the existing list.). The getName() method must return an unique identifier for your extension.

Next we need to tell Twig that we have custom filters we want to use (after registering).

use Silex\Provider\TwigServiceProvider;

$app->register(new TwigServiceProvider(), array(
    'twig.path' => __DIR__ . '/../web/public/views'
));

$app['twig'] = $app->extend("twig", function (\Twig_Environment $twig, Silex\Application $app) {
    $twig->addExtension(new Classes\Utils\Filters($app));

    return $twig;
});