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

时间:2016-01-30 16:59:13

标签: symfony configuration url-routing

我希望用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)还不熟悉,所以我想知道......有没有更好的方法来完成所有路由的附加路由配置?也许有更灵活或更多的“正确”和#34;在Symfony做这些事情的方法?或者我应该挂钩一些现有的机制?

1 个答案:

答案 0 :(得分:2)

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

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似乎不那么狡猾的解决方案

相关问题