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 關注
- 109 瀏覽
添加回答
舉報