如何在将Symfony Routing作为独立使用时缓存路由?

时间:2015-07-04 22:28:03

标签: php symfony caching url-routing

我独立使用Symfony Routing组件,即不使用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框架时会有缓存,这可以在这里轻松实现吗?

1 个答案:

答案 0 :(得分:6)

Symfony Routing Component文档包含如何轻松启用缓存的示例:The all-in-one Router

基本上你的例子可以像下面那样重做:

// 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*/);