亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何以編程方式提供 Symfony 路由參數?

如何以編程方式提供 Symfony 路由參數?

PHP
蠱毒傳說 2023-10-15 15:20:39
在這個 Symfony 路線中/** * @Route("/board/{board}/card/{card}", name="card_show", methods={"GET"}, options={}) */public function show(Board $board, Card $card): Response{    $card->getLane()->getBoard(); // Board instance    // ...}{board}既然參數已經在 中可用,如何以編程方式添加參數{card}?現在,在生成顯示操作的鏈接時,我總是需要添加兩個參數。經過一番研究,我發現 RoutingAutoBundle ( https://symfony.com/doc/master/cmf/bundles/routing_auto/introduction.html#usage ) 可以提供我需要的功能,但它不再適用于 Symfony 5 。謝謝。
查看完整描述

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']


查看完整回答
反對 回復 2023-10-15
  • 1 回答
  • 0 關注
  • 109 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號