php - 我怎样才能找出路由在php中有哪些参数

标签 php symfony twig

背景: 我想修改一个自写的 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/

相关文章:

php - 在php中获取从当前日期开始的周一至周日的上周记录

PHP 类扩展不起作用,为什么这是正确扩展类的方法?

php - 将table1的外键设置在table2的主键的一部分上

symfony - 如何显示自定义的 404 错误页面 - Symfony2

symfony - Twig:允许 HTML,但转义脚本

php - 如何用 Twig 渲染字符串/数据库中的内容?

php - 如何使用product_index改进Magento查询

php - CodeIgniter 日期或日期时间

php - Symfony session 数组在 Controller 中工作正常但在 Twig 中不工作

symfony - 解决关于 $this 的弃用 - get ('twig' )-> getextension ('form' )