我怎样才能找出一条路线在 php 中有哪些参数

How can I find out which parameters a route has in php

背景: 我想修改一个自写的 Twig 扩展。 class定义如下:

class pagination extends \Twig_Extension { 
    protected $generator;

    public function __construct($generator){
        $this->generator = $generator;
    }

    ....
}

在其中一种方法中,我想生成这样的 URL:

$this->generator->generate($route, array('routeParam' => $value);

但问题是,某些路由没有参数 'routeParam',以这种方式生成路由时会导致异常。

我的问题是:如何确定给定路由在该方法中是否具有某些参数?

要检查您的路由是否具有编译路由所需的所有参数,要编译路由,您需要路由器服务,因此通过添加服务定义将 @service_container 服务传递给您的 twig 扩展

somename.twig.pagination_extension:
    class: Yournamesapce\YourBundle\Twig\Pagination
    arguments: [ '@your_generator_service','@service_container'  ]
    tags:
        - { name: twig.extension } ...

然后在你的 class 中获取容器,然后从容器中获取路由器服务,并通过 getRouteCollection() 获取所有路由,一旦你拥有所有路由,通过 $routes->get($route) 获取所需的路由,然后编译这条路线,一旦你有一个合规的路线定义,你可以通过调用 getVariables() 获得路线所需的所有参数,这将 return 参数数组,并且在生成检查数组之前如果 routeParam 存在

use Symfony\Component\DependencyInjection\ContainerInterface as Container;
class Pagination extends \Twig_Extension { 
    protected $generator;
    private $container;
    public function __construct($generator,Container $container){
        $this->generator = $generator;
        $this->container = $container;
    }

    public function somefunction(){
        $routes = $this->container->get('router')->getRouteCollection();
        $routeDefinition = $routes->get($route);
        $compiledRoute = $routeDefinition->compile();
        $all_params = $compiledRoute->getVariables();
        if(in_array('routeParam',$all_params)){
            $this->generator->generate($route, array('routeParam' => $value);
        }
    }
    ....
}