如何使用前缀路由变量?



使用api平台3.1,我试图在我的前缀声明中使用变量:

# config/routes/api_platform.yaml
api_platform:
resource: .
type: api_platform
prefix: /{var}/api

但是因为这个{var}不在操作元数据中,它不是我的实体的一个字段,我得到了这样的消息:Unable to generate an IRI for the item of type *path to my entity*
适用于任何实体的所有操作。

供参考:这个变量被用作'数据库选择器'

所以我正在寻找解决这个问题的方法。
我的目标是在生成路由时在标识符中有这个变量:这里
我试图修改iriConverter或AbstractItemNormalizer,但没有成功。

我最后的希望是覆盖symfony路由器,但它似乎是一个"大事情"。。

因为我需要在所有实体的路由中使用这个{var},一个解决方案是装饰"router.default":

<?php
declare(strict_types=1);
namespace AppDecorator;
use SymfonyComponentDependencyInjectionAttributeAsDecorator;
use SymfonyComponentDependencyInjectionAttributeMapDecorated;
use SymfonyComponentHttpFoundationRequestStack;
use SymfonyComponentHttpKernelCacheWarmerWarmableInterface;
use SymfonyComponentRoutingRequestContext;
use SymfonyComponentRoutingRouter;
use SymfonyComponentRoutingRouterInterface;
#[AsDecorator(decorates: 'router.default')]
class DecoratorRouter implements RouterInterface, WarmableInterface
{
public function __construct(#[MapDecorated] private Router $originalRouter, private RequestStack $requestStack)
{
}
public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string
{
$request = $this->requestStack->getCurrentRequest();
if ($request && $request->attributes->has('var')) {
$parameters['var'] = $request->attributes->get('var');
}
return $this->originalRouter->generate($name, $parameters, $referenceType);
}
public function getRouteCollection()
{
return $this->originalRouter->getRouteCollection();
}
public function match(string $pathinfo): array
{
return $this->originalRouter->match($pathinfo);
}
public function setContext(RequestContext $context)
{
return $this->originalRouter->setContext($context);
}
public function getContext(): RequestContext
{
return $this->originalRouter->getContext();
}
public function warmUp(string $cacheDir)
{
return $this->originalRouter->warmUp($cacheDir);
}
}