将路由配置附加到所有路由

Appending route configuration to all routes

我想用 Symfony 制作多语言网站。所以我需要添加如下内容:

# app/config/routing.yml
contact:
    path:     /{_locale}
    defaults: { _locale: "pl" }
    requirements:
        _locale: pl|en 

但是我不想在我定义的每条路线上重复这个,所以我想出了解决方案:

# app/config/config.yml
parameters:
    locale.available: pl|en
    locale.default: pl
<...>
router:
    resource: "%kernel.root_dir%/config/routing.php" # note '.php'

<!-- language: lang-php -->
# app/config/routing.php
<?php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Yaml\Parser;

$configFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'routing.yml';
$yaml = new Parser();
try {
    $routes = $yaml->parse(file_get_contents($configFile));
} catch (ParseException $e) {
    printf("Unable to parse the YAML string: %s", $e->getMessage());
}
$collection = new RouteCollection();
foreach ($routes as $name => $def) {
    $route = new Route($def['path']);
    foreach (['defaults', 'requirements', 'options', 'host', 'schemes', 'methods', 'condition'] as $opt) {
        $mtd = 'add'. ucfirst($opt);
        if(isset($def[$opt])) $route->$mtd($def[$opt]);
    }
    $collection->add($name, $route);
}
$collection->addRequirements(['_locale' => "%locale.available%"]);
$collection->addDefaults(['_locale'=>"%locale.default%"]);

return $collection;
?>

# app/config/routing_dev.yml
<...>
_main:
    resource: routing.php

不过,我还是 Symfony2(现在是 3)的新手,所以我想知道...有没有更好的方法来完成将路由配置附加到所有路由?也许在 Symfony 中有更灵活或更多 "right" 的方式来做这些事情?或者我应该挂钩到一些现有的机制?

您可以使用扩展默认路由的自定义路由加载器。有关详细信息,请参阅此处:

http://symfony.com/doc/current/cookbook/routing/custom_route_loader.html

例如,如果你想支持 yml、xml 和注释,你需要扩展 Symfony\Component\Routing\Loader\YamlFileLoader、Symfony\Component\Routing\Loader\XmlFileLoader 和 Sensio\Bundle\FrameworkExtraBundle\Routing\AnnotatedRouteControllerLoader 合并你必须的逻辑加载方法,你需要改变 sensio_framework_extra.routing.loader.annot_class.class,routing.loader.yml.class and routing.loader.xml.class 指向新 类.

的参数

定义您自己的 route_loader 似乎是不那么棘手的解决方案