在Symfony 3.2中,路由组件已被改进为支持在路由paths和requirements条件中支持UTF-8字符。得益于全新的utf8路由选项,你可以让Symfony匹配和生成UTF-8字符:

1
2
3
4
5
6
7
8
9
10
11
12
13
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
 
/**
 * @Route(
 *     "/category/{name}",
 *     "requirements" = { "name": ".+" },
 *     "options" = { "utf8": true }
 * )
 */
public function categoryAction($name)
{
    // ...
}

上面路由中,utf8选项设为了true,令Symfony认为.条件可以匹配任何UTF-8字符,而不是仅去匹配一个single byte字符,所以,以下的URLs将被匹配:/category/日本語/category/فارسی/category/한국어等等。万一你还感到迷惑,当知此选项同样支持匹配URLs中的emojis表情符。

在Symfony 3.2中,没有必要显式地设置这个utf8。Symfony只要在路由路径(route paths)和正则条件(requirements)中一发现UTF-8字符,它就会自动地开启UTF-8支持:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * 'utf8' is set to 'true' automatically because of the
 * contents of the 'name'  requirements:
 *
 * @Route(
 *     "/category/{name}",
 *     "requirements" = { "name": "日本語|فارسی" }
 * )
 */
public function categoryAction($name)
{
    // ...
}

不过,我们再次希望事情能够显式化,这种行为需要被抑制(deprecated),在Symfony4.0中这将导致一个LogicException。因此,请牢记当需要时在任何路由中显式地定义utf8选项。

除了UTF-8字符,路由组件也支持全部的PCRE Unicode properties,它可以转义那些匹配了通用字符类型(generic character types)的顺序。例如,\p{Lu}匹配任何语言中的大写字符,\p{Greek}匹配任何希腊字符,\P{Han}匹配任何没被包括在中国汉语脚本中的字符,等等。(译注:原文即是matches any character not included in the Chinese Han script)