Skip to content

Commit e950470

Browse files
committed
Управление кэшированием роутов
1 parent 975a885 commit e950470

File tree

5 files changed

+48
-21
lines changed

5 files changed

+48
-21
lines changed

DependencyInjection/Configuration.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public function getConfigTreeBuilder(): TreeBuilder
2727
->scalarNode('router_request_context_host')->defaultValue('%kernel.site.host%')->end()
2828
->scalarNode('router_request_context_scheme')->defaultValue('http')->end()
2929
->scalarNode('router_request_context_base_url')->defaultValue('')->end()
30-
->scalarNode('router_cache_path')->defaultValue('%kernel.cache_dir%/routes')->end()
30+
->scalarNode('router_cache_path')->defaultValue(null)->end()
3131
->scalarNode('router_config_file')->defaultValue('app/routes.yaml')->end()
3232
->booleanNode('router_check_exists_controller')->defaultValue(false)->end()
3333
->arrayNode('controller_annotations_path')

DependencyInjection/WpSymfonyRouterExtension.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,5 +167,14 @@ private function registerRouterConfiguration(
167167
new Reference('routing.loader.annotation'),
168168
]);
169169
}
170+
171+
// Применить кэширование роутов, если это задано опцией.
172+
if ($config['router_cache_path']) {
173+
$routerDefinition = $container->getDefinition('router');
174+
$routerDefinition->addMethodCall(
175+
'setConfigCacheFactory',
176+
[new Reference('config_cache_factory')]
177+
);
178+
}
170179
}
171180
}

Resources/config/services.yaml

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,11 @@ services:
3232
- '@routing.loader'
3333
- '%kernel.project_dir%/%router.config.file%'
3434
- debug: '%kernel.debug%'
35-
# cache_dir: '%router.cache.path%'
35+
cache_dir: '%router.cache.path%'
36+
generator_class: Symfony\Component\Routing\Generator\CompiledUrlGenerator
37+
generator_dumper_class: Symfony\Component\Routing\Generator\Dumper\CompiledUrlGeneratorDumper
38+
matcher_class: Symfony\Bundle\FrameworkBundle\Routing\RedirectableCompiledUrlMatcher
39+
matcher_dumper_class: Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper
3640
- '@request.context'
3741

3842
router.default: '@router'
@@ -54,7 +58,7 @@ services:
5458
symfony_router:
5559
class: Prokl\WpSymfonyRouterBundle\Services\Router\InitRouter
5660
arguments:
57-
- '@routes.collection'
61+
- '@router'
5862
- '@json.error.controller'
5963
- '@event_dispatcher'
6064
- '@controller_resolver'
@@ -72,6 +76,22 @@ services:
7276

7377
symfony.get.routes: '@routes.collection'
7478

79+
config.resource.self_checking_resource_checker:
80+
class: Symfony\Component\Config\Resource\SelfCheckingResourceChecker
81+
tags:
82+
- { name: config_cache.resource_checker, priority: -990 }
83+
84+
dependency_injection.config.container_parameters_resource_checker:
85+
class: Symfony\Component\DependencyInjection\Config\ContainerParametersResourceChecker
86+
arguments: ['@service_container']
87+
tags:
88+
- { name: config_cache.resource_checker, priority: -980 }
89+
90+
config_cache_factory:
91+
class: Symfony\Component\Config\ResourceCheckerConfigCacheFactory
92+
arguments:
93+
- !tagged_iterator config_cache.resource_checker
94+
7595
Symfony\Component\HttpKernel\Controller\ControllerResolver: ~
7696

7797
Prokl\WpSymfonyRouterBundle\Services\Controllers\RedirectingController: ~
@@ -134,10 +154,6 @@ services:
134154
# Фасад. Сработает только, если активирован бандл Facade-Bundle.
135155
Prokl\WpSymfonyRouterBundle\Services\Facades\RunRoute: ~
136156

137-
# Нативный сервис из Symfony.
138-
config_cache_factory:
139-
class: Symfony\Component\Config\ResourceCheckerConfigCacheFactory
140-
141157
# Утилиты для работы с роутами.
142158
routing.utils:
143159
class: Prokl\WpSymfonyRouterBundle\Services\Utils\RouteChecker

Services/Router/InitRouter.php

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,14 @@
1010
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
1111
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
1212
use Symfony\Component\HttpKernel\HttpKernel;
13-
use Symfony\Component\Routing\Matcher\UrlMatcher;
14-
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
1513
use Symfony\Component\Routing\RequestContext;
1614
use Symfony\Component\Routing\RouteCollection;
1715
use Symfony\Component\HttpFoundation\RequestStack;
1816
use Symfony\Component\HttpFoundation\Request;
1917
use Symfony\Component\HttpKernel\EventListener\ErrorListener;
2018
use Symfony\Component\HttpKernel\EventListener\ResponseListener;
2119
use Symfony\Component\HttpKernel\EventListener\RouterListener;
20+
use Symfony\Component\Routing\RouterInterface;
2221

2322
/**
2423
* Class InitRouter
@@ -37,6 +36,7 @@
3736
* @since 06.03.2021 Инициация события kernel.terminate.
3837
* @since 21.03.2021 URL matcher опционально пробрасывается снаружи.
3938
* @since 03.05.2021 Обработка исключений события kernel.terminate.
39+
* @since 24.07.2021 Поддержка кэширования роутов.
4040
*/
4141
class InitRouter
4242
{
@@ -45,6 +45,11 @@ class InitRouter
4545
*/
4646
private static $bundlesRoutes = [];
4747

48+
/**
49+
* @var RouterInterface $router Router.
50+
*/
51+
private $router;
52+
4853
/**
4954
* @var RouteCollection $routeCollection Коллекция роутов.
5055
*/
@@ -97,29 +102,29 @@ class InitRouter
97102
* @since 19.11.2020 RequestStack пробрасывается снаружи.
98103
* @since 21.03.2021 URL matcher опционально пробрасывается снаружи.
99104
*
100-
* @param RouteCollection $routeCollection Коллекция роутов.
105+
* @param RouterInterface $router Роутер.
101106
* @param ErrorControllerInterface $errorController Error controller.
102107
* @param EventDispatcherInterface $eventDispatcher Event dispatcher.
103108
* @param ControllerResolverInterface $controllerResolver Controller resolver.
104109
* @param ArgumentResolverInterface $argumentResolver Argument resolver.
105110
* @param Request $request Request приложения.
106111
* @param RequestStack $requestStack Request stack.
107-
* @param UrlMatcherInterface|null $urlMatcher URL matcher.
108112
*/
109113
public function __construct(
110-
RouteCollection $routeCollection,
114+
RouterInterface $router,
111115
ErrorControllerInterface $errorController,
112116
EventDispatcherInterface $eventDispatcher,
113117
ControllerResolverInterface $controllerResolver,
114118
ArgumentResolverInterface $argumentResolver,
115119
Request $request,
116-
RequestStack $requestStack,
117-
UrlMatcherInterface $urlMatcher = null
120+
RequestStack $requestStack
118121
) {
119122
$this->request = $request;
120123
$this->resolver = $controllerResolver;
121124
$this->argumentResolver = $argumentResolver;
122-
$this->routeCollection = $routeCollection;
125+
126+
$this->router = $router;
127+
$this->routeCollection = $router->getRouteCollection();
123128

124129
$this->requestStack = $requestStack;
125130
$this->requestStack->push($request);
@@ -132,11 +137,7 @@ public function __construct(
132137
$this->mixRoutesBundles();
133138

134139
// Инициализация необходимого для запуска роутера.
135-
$matcher = $urlMatcher ?? new UrlMatcher(
136-
$this->routeCollection,
137-
$requestContext
138-
);
139-
140+
$matcher = $this->router->getMatcher();
140141
$matcher->setContext($requestContext);
141142

142143
$this->dispatcher = $eventDispatcher;

readme.MD

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717

1818
- `enabled` - Использовать бандл. По умолчанию `true`.
1919
- `controller_annotations_path` - массив с путями к контроллерам, использующим аннотации.
20-
- `router_cache_path` - путь к кэшу аннотаций. По умолчанию `%kernel.cache_dir%/routes`.
20+
- `router_cache_path` - путь к кэшу аннотаций (вида `%kernel.cache.dir%/routes`). По умолчанию `null`.
21+
Если задан, то роуты будут кэшироваться.
2122
- `router_config_file` - путь к файлу с конфигурацией роутов. По умолчанию `app/routes.yaml`. Файл может быть в любом поддерживаемом Symfony формате - Yaml, PHP, XML и т.д.
2223
- `router_check_exists_controller` - проверять на существование классы-контроллеры. По умолчанию `false`.
2324
- `resource` - путь к конфигурационному файлу роутов. По умолчанию: `%kernel.project_dir%/app/routes.yaml`.

0 commit comments

Comments
 (0)