当使用Symfony路由作为独立路由时,如何缓存路由


How to cache routes when using Symfony Routing as a standalone?

我使用的是独立的Symfony路由组件,即不使用Symfony框架。这是我正在玩的基本代码:

<?php
$router = new Symfony'Component'Routing'RouteCollection();
$router->add('name', new Symfony'Component'Routing'Route(/*uri*/));
// more routes added here
$context = new Symfony'Component'Routing'RequestContext();
$context->setMethod(/*method*/);
$matcher = new Symfony'Component'Routing'Matcher'UrlMatcher($router, $context);
$result = $matcher->match(/*requested path*/);

有没有一种方法可以缓存路由,这样我就不需要在每次页面加载时运行所有的add()调用?(例如参见FastRoute。(我相信在使用完整的Symfony框架时会有缓存,在这里可以轻松实现吗?

Symfony路由组件文档包含一个如何轻松启用缓存的示例:一体式路由器

基本上,你的例子可以像下面这样修改:

// RouteProvider.php
use Symfony'Component'Routing'RouteCollection;
use Symfony'Component'Routing'Route;
$collection = new RouteCollection();
$collection->add('name', new Route(/*uri*/));
// more routes added here
return $collection;
// Router.php
use Symfony'Component'Config'FileLocator;
use Symfony'Component'Routing'RequestContext
use Symfony'Component'Routing'Loader'PhpFileLoader;
$context = new RequestContext();
$context->setMethod(/*method*/);
$locator = new FileLocator(array(__DIR__));
$router = new Router(
    new PhpFileLoader($locator),
    'RouteProvider.php',
    array('cache_dir' => __DIR__.'/cache'), // must be writeable
    $context
);
$result = $router->match(/*requested path*/);