PHP Silex routing localization

青春壹個敷衍的年華 提交于 2020-01-02 06:47:07

问题


starting with Silex.

Say I want a localised site where all routes have to start with /{_locale} and don't fancy repeating myself as :

$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'd like to create a base route that would match the locale and subclass it in some way but couldn't figure out by myself how to trigger that in an elegant way.


回答1:


I think you can delegate the local detection with mount function:

You mount a route for each local you want to support, but they redirect to the same controller:

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

And now the 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;
    }

}


来源:https://stackoverflow.com/questions/26673037/php-silex-routing-localization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!