Set locale for Symfony 2.5 application (force locale)

元气小坏坏 提交于 2020-01-26 03:12:08

问题


I would like to force locale for my Symfony 2.5 application to ru_RU.UTF-8. I want this locale to be used for strftime() function.

I have the following configuration in my app/config.yml:

framework:
    default_locale: "ru_RU.UTF-8"

I'm using the following code in one of my controllers to debug this:

//setlocale(LC_TIME, 'ru_RU.UTF-8');
var_dump(setlocale(LC_TIME, 0));
var_dump(strftime('%B', time()));
die();

When executed like this, it shows: string(1) "C" string(6) "August".

However, when first line is uncommented it shows: string(11) "ru_RU.UTF-8" string(12) "Август", so the locale is installed in the system and works correctly.

Ho do I make Symfony to always use locale specified in the config?


$ locale -a:

C
C.UTF-8
en_US.utf8
POSIX
ru_RU
ru_RU.iso88595
ru_RU.utf8

回答1:


The locale setting for Symfony doesn't influence the PHP settings, it's only a Symfony setting.

You have to use setlocale() to configure PHP's locale. You can place this in the front controllers (web/app.php and web/app_dev.php) or create a listener for kernel.request.




回答2:


Any solution based on setlocale() (as in @Wouter J's answer) will sooner or later give you a headache, since it relies on the locale setting of the current machine. So whenever you switch server, it might stop working. And it can differ between your development and production server.

A better approach is to drop strftime() in favor of IntlDateFormatter::formatObject:

\IntlDateFormatter::formatObject($entity->getTimestamp(), \IntlDateFormatter::FULL, 'de_AT');

This only requires that you have the PHP intl extension installed. There's also a Symfony replacement for PHP's native \IntlDateFormatter but I guess that's only necessary if you don't have the intl extension available.

For Twig you can use the localizeddate filter. Installation instructions: https://stackoverflow.com/a/24390635/1668200



来源:https://stackoverflow.com/questions/25290292/set-locale-for-symfony-2-5-application-force-locale

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