如何包容外部路由资源
所有的路由都通过一个单一的配置文件加载-通常是app/config/routing.yml
(请看加载路由)。但是,如果你使用Annotation路由,你需要用Annotation将路由指向到到控制器。这可以通过“importing”导入目录到路由配置中来实现:
|
# app/config/routing.yml
app:
resource: '@AppBundle/Controller/'
type: annotation # required to enable the Annotation reader for this resource |
|
<!-- app/config/routing.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="Http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing
http://symfony.com/schema/routing/routing-1.0.xsd">
<!-- the type is required to enable the annotation reader for this resource -->
<import resource="@AppBundle/Controller/" type="annotation"/>
</routes> |
|
// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;
$collection = new RouteCollection();
$collection->addCollection(
// second argument is the type, which is required to enable
// the annotation reader for this resource
$loader->import("@AppBundle/Controller/", "annotation")
);
return $collection; |
当从YAML导入资源时,根键(如app
)是没有意义的。只要保证它是唯一的,没有其它行覆盖它即可。
resource
键用来加载指定的路由资源。在本例中,资源是一个目录,其@AppBundle
快捷语法能够解析AppBundle的完整路径。当路由指定一个目录时,该目录中的所有文件都会被解析到路由中去。
你还可以包容其他路由配置文件,以下方法经常用来导入第三方路由:
|
# app/config/routing.yml
app:
resource: '@AcmeOtherBundle/Resources/config/routing.yml' |
|
<!-- app/config/routing.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing
http://symfony.com/schema/routing/routing-1.0.xsd">
<import resource="@AcmeOtherBundle/Resources/config/routing.xml" />
</routes> |
|
// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;
$collection = new RouteCollection();
$collection->addCollection(
$loader->import("@AcmeOtherBundle/Resources/config/routing.php")
);
return $collection; |
在引入的路由中加前缀 ¶
你也可以选择为导入的路由提供一个“prefix”前缀。例如,假设你希望在AppBundle的所有路由中使用前缀/site
( 如用/site/blog/{slug}
代替 /blog/{slug}
):
|
# app/config/routing.yml
app:
resource: '@AppBundle/Controller/'
type: annotation
prefix: /site |
1
2
3
4
5
6
7
8
9
10
11
12
|
<!-- app/config/routing.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing
http://symfony.com/schema/routing/routing-1.0.xsd">
<import
resource="@AppBundle/Controller/"
type="annotation"
prefix="/site" />
</routes> |
|
// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;
$app = $loader->import('@AppBundle/Controller/', 'annotation');
$app->addPrefix('/site');
$collection = new RouteCollection();
$collection->addCollection($app);
return $collection; |
从新的路由资源中加载的每一个路由之路径,现在都被添加了/site
字符串前缀。
添加一个需要的主机并引入到路由 ¶
你可以在引入的路由中设置主机的正则表达式。参考如何基于Host来匹配路由了解详情。