PHP Silex Routing Localization

starting with Silex.

Let's say I need a localized site where all routes should start with /{_locale}and don't need to repeat themselves like:

$app->match('/{_locale}/foo', function() use ($app) {
return $app['twig']->render('foo.twig');
})
->assert('_locale', implode('|', $app['languages.available']))
->value('_locale', $app['locale.default'])
->bind('foo');

$app->match('/{_locale}/bar', function() use ($app) {
    return $app['twig']->render('bar.twig');
    })
    ->assert('_locale', implode('|', $app['languages.available']))
    ->value('_locale', $app['locale.default'])
    ->bind('bar');

Ideally, I would like to create a basic route that would somehow correspond to the language and subclass, but I myself could not figure out how to gracefully call it.

+4
source share
1 answer

I think you can delegate local discovery using a function mount:

You mount the route for each local user that you want to support, but are redirected to the same controller:

    $app->mount('/en/', new MyControllerProvider('en'));
    $app->mount('/fr/', new MyControllerProvider('fr'));
    $app->mount('/de/', new MyControllerProvider('de'));

And now local can be an attribute of your controller:

class MyControllerProvider implements ControllerProviderInterface {

    private $_locale;

    public function __construct($_locale) {
        $this->_locale = $_locale;
    }

    public function connect(Application $app) {
        $controler = $app['controllers_factory'];


        $controler->match('/foo', function() use ($app) {
                            return $app['twig']->render('foo.twig');
                        })
                ->bind('foo');

        $controler->match('/bar', function() use ($app) {
                            return $app['twig']->render('bar.twig');
                        })
                ->bind('bar');

        return $controler;
    }

}
+5
source

All Articles