Last Updated: February 25, 2016
·
6.848K
· MidnightLightning

Silex Global variables

When working with a Silex application, I've run into a few times where I need a value to persist through the application and into the template of the page, and in my learning, found a few ways to do so.

Twig Globals

If you're using the Twig template Provider to render pages, you can use a global variable:

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/views',
));
$app['twig']->addGlobal('foo', $bar);

That sets the template variable {{ foo }} the moment the addGlobal() method is called. You can override the global by calling the addGlobal() method again, but this can get very tedious if there's many variables to set. And if you need access to foo before the template (somewhere else in the Controller logic), it's not possible to get access to it once it's set.

Silex Application container

The Silex application allows storing arbitrary values, and then recalling them, but you then need to remember to pass them on to the template:

$app['foo'] = $bar;
echo $app['foo'];

return $app['twig']->render('mypage.twig', array('foo' => $app['foo']));

<strong>FALSE!</strong> That is the wrong approach, and the trap I fell into the first time, and devised various ways to not forget to pass the variable on to the template. The proper method is to realize that the $app variable is already passed to the template, along with its custom-set attributes. So, once you set $app['foo'] in the Controller (PHP), in the View (Twig) file, you just need to call {{ app.foo }}.