如何从路由获取区域设置并在服务控制器中使用它?
这是我的服务控制器:
$app['clients.controller'] = function() use ($app) {
$clientTranslator = new ClientTranslator;
$translations = $clientTranslator->getTranslations();
foreach ($translations as $domain => $data) {
foreach ($data as $locale => $messages) {
$app['translator']->addResource('array', $messages, $locale, $domain);
}
}
$app['translator']->setLocale($app['locale']);
return new ClientController($app, $app['clients.model'], $app['clients.validator']);
};
请注意,我正在尝试从应用程序区域设置设置转换程序区域设置。
以下是调用此服务控制器的路由:
$app->mount ( '/en', function ($client) use ($app) {
$app ['locale'] = "en";
$client->match ( '/{id}/edit', 'clients.controller:editAction')
->assert ( 'id', '\d+' )
->method ( 'GET|POST' );
$client->match ( '/add', 'clients.controller:addAction')
->method ( 'GET|POST' );
$client->match ( '/{id}', 'clients.controller:deleteAction' )
->assert ( 'id', '\d+' )
->method ( 'DELETE' );
$client->get('/', "clients.controller:indexAction");
});
$app->mount('/fr', function ($client) use ($app) {
$app['locale'] = "fr";
$client->match ( '/{id}/edit', 'clients.controller:editAction')
->assert ( 'id', '\d+' )
->method ( 'GET|POST' );
$client->match ( '/add', 'clients.controller:addAction' )
->method ( 'GET|POST' );
$client->match ( '/{id}', 'clients.controller:deleteAction' )
->assert ( 'id', '\d+' )
->method ( 'DELETE' );
$client->get ( '/', "clients.controller:indexAction" );
} );
现在发生的事情是应用程序区域设置始终是法语。我现在明白,即使没有调用该路由,也会执行mount部分中的语句。
实现我想要的正确方法是什么?
由于
答案 0 :(得分:0)
在这种情况下,路线的正确方法如下
$app->mount ( '{_locale}/', function ($client) use ($app) {
$client->match ( '/{id}/edit', 'clients.controller:editAction')
->assert ( 'id', '\d+' )
->method ( 'GET|POST' );
$client->match ( '/add', 'clients.controller:addAction')
->method ( 'GET|POST' );
$client->match ( '/{id}', 'clients.controller:deleteAction' )
->assert ( 'id', '\d+' )
->method ( 'DELETE' );
$client->get('/', "clients.controller:indexAction");
});
这样就可以自动设置语言环境。