Tag Archives: twig

Photolib 2

Today I was doing household stuff for Photolib. Well, it still needs some facelifting, but the good stuff was happening on the background.

I am using PHP built-in web server (available since 5.4) to test photolib. But since ‘photos’ is a folder and I run server like this “php -S 127.0.0.1:8080 index.php”, to ensure all request captured by index.php, thus my development environment lacks base URL (/photos/) and everything breaks. The solution would be to use separate configuration for development and for production. That’s kind of usual stuff, I just never actually did it with Silex before. Turns out it’s pretty easy.

First, have to get configuration service provider, like ConfigServiceProvider.
Second, create two configuration files: prod.yml and dev.yml.
Third, add configuration to the application:

// index.php
$app = new Silex\Application();
$env = getenv('APP_ENV') ?: 'prod';
$app->register(new Igorw\Silex\ConfigServiceProvider(__DIR__."/app/conf/{$env}.yml"));

Now, we can enable debug for development, by simply putting the line

# dev.yml
debug: true

into dev.yml. Alright, moving on to Twig.

Which is a little bit trickier. TwigServiceProvider in Silex knows nothing about configuration provider, so need to tell it that we have some settings for it:

// index.php

// Save globals for future use
$twigGlobals = $app['twig']['globals'];

// Register twig as a service
$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__."/app/twig",
));
// Extend twig service by adding global variables
$app['twig'] = $app->share($app->extend('twig', function($twig, $app) use ($twigGlobals) {
    foreach ($twigGlobals as $k => $g) {
        $twig->addGlobal($k, $g);
    }

    return $twig;
}));

And in config file:

# prod.yml
twig:
  globals:
    base_url: /photos/

Now just use {{ base_url }} in templates. Best way to do it would be to allow Twig service provider to accept ‘twig.globals’ as an option (like it does with ‘twig.path’) but that will have to wait until next time.

That’s it for today.

As a bonus, here is an excellent example of banner double hit in iAlien application:


I want adblock for iOS too.

imagine reading that on iPhone 4 screen