Symfony 6.2路由-检查参数是否与数据库中的行匹配

f5emj3cl  于 2023-05-29  发布在  其他
关注(0)|答案(1)|浏览(111)

在symfony 6.2中,我如何才能做到这一点,调用一个方法来检查第一个参数是否匹配数据库中的某个参数?
我尝试设置一个服务来设置一个自定义路由加载器,但我无法添加所有的路由,它只添加了最后一个。
这是我的服务:

<?php

namespace App\Service;

use App\Entity\Country;
use Doctrine\Common\DataFixtures\Loader;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Routing\RouteLoaderInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Router;
use Symfony\Component\Routing\RouterInterface;

class RouteHandler implements RouteLoaderInterface
{

    private $managerRegistry;

    private $router;

    private $isLoaded = false;

    public function __construct(RouterInterface $router, ManagerRegistry $managerRegistry)
    {
        $this->router = $router;
        $this->managerRegistry = $managerRegistry;
    }

    public function __invoke(): RouteCollection
    {
        if (true === $this->isLoaded) {
            throw new \RuntimeException('Do not add the routes twice');
        }

        $countries = $this->managerRegistry->getRepository(Country::class)->findAll();

        $routes = new RouteCollection();
        foreach ($countries as $country) {
            $name = strtolower($country->getName());
            $acronym = strtolower($country->getAcronym());
            $path = "/{$acronym}";
            $defaults = [
                '_controller' => 'App\Controller\Country::index',
            ];

            $route = new Route($path, $defaults, []);
            $routeName = "app_country";
            $routes->add($routeName, $route);
        }

        $this->isLoaded = true;

        return $routes;
    }
}

我的当前路线。yaml:

controllers:
    resource:
        path: ../src/Controller/
        namespace: App\Controller
    type: attribute

country_routes:
    resource: 'App\Service\RouteHandler'
    type: service

我的服务

services:
    _defaults:
        autowire: true
        autoconfigure: true
    App\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'

    App\Service\RouteHandler:
        class: App\Service\RouteHandler
        arguments: [ '@router.default','@doctrine' ]
bin/console debug:router

只返回一个app_country的示例,我希望每个国家都有一个,我该怎么做?

lx0bsm1f

lx0bsm1f1#

好的,看起来我需要使用$routes->addCollection($routes)并更改路由名称以包含指定的行

相关问题