PHP Silex路由本地化 [英] PHP Silex routing localization
本文介绍了PHP Silex路由本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从Silex开始.
说我想要一个本地化的站点,在该站点中所有路由都必须以/{_locale}
开头,并且不要幻想将自己重复为:
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.
推荐答案
我认为您可以使用mount
函数委派本地检测:
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;
}
}
这篇关于PHP Silex路由本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文