1 回答
TA贡献1801条经验 获得超8个赞
我的控制器操作(带@Route注释)如下所示:
/**
* @Route("/board/{board}/card/{card}", name="card_show", methods={"GET"})
*/
public function show(Card $card): Response
{
}
$card我们在方法签名中只有一个参数 ( ),但在路由中只有两个参数。
这是在 twig 中调用路由的方法:
path("card_show", {card: card.id})
无需board参数,这要归功于自定义路由器。
这是自定义路由器的样子:
<?php // src/Routing/CustomCardRouter.php
namespace App\Routing;
use App\Repository\CardRepository;
use Symfony\Component\Routing\RouterInterface;
class CustomCardRouter implements RouterInterface
{
private $router;
private $cardRepository;
public function __construct(RouterInterface $router, CardRepository $cardRepository)
{
$this->router = $router;
$this->cardRepository = $cardRepository;
}
public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
{
if ($name === 'card_show') {
$card = $this->cardRepository->findOneBy(['id' => $parameters['card']]);
if ($card) {
$parameters['board'] = $card->getLane()->getBoard()->getId();
}
}
return $this->router->generate($name, $parameters, $referenceType);
}
public function setContext(\Symfony\Component\Routing\RequestContext $context)
{
$this->router->setContext($context);
}
public function getContext()
{
return $this->router->getContext();
}
public function getRouteCollection()
{
return $this->router->getRouteCollection();
}
public function match($pathinfo)
{
return $this->router->match($pathinfo);
}
}
board现在,通过注入和使用卡存储库以编程方式提供缺少的参数。要启用自定义路由器,您需要在 services.yaml 中注册它:
App\Routing\CustomCardRouter:
decorates: 'router'
arguments: ['@App\Routing\CustomCardRouter.inner']
- 1 回答
- 0 关注
- 85 浏览
添加回答
举报