php - 独立使用 Symfony Routing 时如何缓存路由?

标签 php symfony caching url-routing

我正在独立使用 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 路由组件文档包含一个如何轻松启用缓存的示例: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*/);

关于php - 独立使用 Symfony Routing 时如何缓存路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31225578/

相关文章:

高速缓冲存储器和存储器地址

php - Sonata FormMapper 从整数字段添加链接

php - 将命名空间属性添加到php中的xml节点

脚本终止前的 PHP 回调

php - Twig:从配置文件中添加 Twig 扩展调试

caching - 使用 Symfony2,为什么缓存响应中的 ESI 标签会被忽略?

php - 如何在 Slim 3 中手动启动 404 处理程序?

Symfony2 全局/站点范围 Assets

php - Symfony2 : Duplicate definition of column 'id' on entity in a field or discriminator column mapping

c++ - 对两个连续测量进行基准测试时不一致