背景: 我想修改一个自写的 Twig 扩展。 该类定义如下:
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 } ...
然后在你的类中获取容器,然后从容器中获取路由器服务,并通过 getRouteCollection()
获取所有路由,一旦所有路由都通过 $routes->get 获取所需的路由($route)
然后编译该路由,一旦你有一个编译的路由定义,你可以通过调用 getVariables()
获取路由所需的所有参数,这将返回参数数组并在生成之前如果 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);
}
}
....
}
关于php - 我怎样才能找出路由在php中有哪些参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31702433/