按照https://github.com/FriendsOfSymfony/FOSUserBundle/issues/2751的建議,我實現了一個緩存映射,以便將路由名解析爲控制器類和方法。
<?php
// src/Cache/RouteClassMapWarmer.php
namespace App\Cache;
use Symfony\Component\Cache\Simple\PhpFilesCache;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\Routing\RouterInterface;
class RouteClassMapWarmer implements CacheWarmerInterface
{
/** @var ContainerInterface */
protected $container;
/** @var RouterInterface */
protected $router;
public function __construct(ContainerInterface $container, RouterInterface $router)
{
$this->container = $container;
$this->router = $router;
}
public function warmUp($cacheDirectory)
{
$cache = new PhpFilesCache('route_class_map', 0, $cacheDirectory);
$controllers = [];
foreach ($this->router->getRouteCollection() as $routeName => $route) {
$controller = $route->getDefault('_controller');
if (false === strpos($controller, '::')) {
list($controllerClass, $controllerMethod) = explode(':', $controller, 2);
// service_id gets resolved here
$controllerClass = get_class($this->container->get($controllerClass));
}
else {
list($controllerClass, $controllerMethod) = explode('::', $controller, 2);
}
$controllers[$routeName] = ['class' => $controllerClass, 'method' => $controllerMethod];
}
unset($controller);
unset($route);
$cache->set('route_class_map', $controllers);
}
public function isOptional()
{
return false;
}
}
而且在我RouteHelper,閱讀本實施看起來是這樣的
$cache = new PhpFilesCache('route_class_map', 0, $this->cacheDirectory);
$controllers = $cache->get('route_class_map');
if (!isset($controllers[$routeName])) {
throw new CacheException('No entry for route ' . $routeName . ' forund in RouteClassMap cache, please warmup first.');
}
if (null !== $securityAnnotation = $this->annotationReader->getMethodAnnotation((new \ReflectionClass($controllers[$routeName]['class']))->getMethod($controllers[$routeName]['method']), Security::class))
{
return $this->securityExpressionHelper->evaluate($securityAnnotation->getExpression(), ['myParameter' => $myParameter]);
}
這應該是比獲得routeCollection快得多和解決的service_id:方法譜寫_controller的屬性對每個容器請求。
我相信沒有任何其他的選擇可以更高效。你需要怎麼處理類名? – Gerry
我想重現本教程:https://www.trisoft.ro/blog/6-symfony2-advanced-menus我需要className才能讀取元數據:$ this-> metadataReader-> loadMetadataForClass(new \ ReflectionClass($類)); – iBadGamer
我想你可以添加一個_controller_classname參數給你的路線。但是需要控制器類名稱來生成菜單似乎不是理想的設計。 – Cerad