草庐IT

php - Symfony2 - 如何为每个请求或生成的 URL 的路由添加一个全局参数,类似于 _locale?

coder 2024-04-06 原文

我尝试添加全局参数

所有路由的参数,以及内核Request Listener中的参数设置。

路由

mea_crm:
    resource: @Crm4Bundle/Resources/config/routing.yml
    prefix: /{_applicationid}
    defaults:  { _applicationid: 0 }
    requirements:
      _applicationid: |0|1|2|3|4|5|6

在 Listener - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest } 我尝试设置这个参数

$request->attributes->add(array(
            '_applicationid'=>$appCurrentId
        ));
        $request->query->add(
            array(
                '_applicationid'=>$appCurrentId
            )
        );
$request->query->set('_applicationid',$appCurrentId);

并且仍然在路由中 - 默认值 0

更新 1 我将监听器设置为最大优先级

tags:
     - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 255 }

在监听器设置中

 public function onKernelRequest(GetResponseEvent $event)
    {

        $event->getRequest()->request->set('_applicationid',1);

        return ;

还没有这个参数就是路由。

更新 2

这很奇怪 - 我转储到 Symfony\Component\Routing\Router

在方法中

public function matchRequest(Request $request)
....
var_dump($matcher->matchRequest($request));
        die();

得到

数组(大小=4) '_controller' => string 'Mea\TaskBundle\Controller\TaskListController::viewOneAction'(长度=59) '_applicationid' => 字符串 '1' (长度=1) 'id' => 字符串 '700' (长度=3) '_route' => 字符串 'MeaTask_View' (length=12)

所以存在_applicationid

但在网址中我没有它

这里是routing.yml

mea_crm:
    resource: @MeaCrm4Bundle/Resources/config/routing.yml
    prefix: /{_applicationid}
    defaults:  { _applicationid: null }
    requirements:
      _applicationid: |1|2|3|4|5|6

我有这样的链接:http://crm4.dev/app_dev.php//u/logs/list 有任何想法吗 ?

更新 3

这是我的听众

php app/console debug:event-dispatcher kernel.request

Registered Listeners for "kernel.request" Event
===============================================

 ------- ---------------------------------------------------------------------------------- ---------- 
  Order   Callable                                                                           Priority  
 ------- ---------------------------------------------------------------------------------- ---------- 
  #1      Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure()      2048      
  #2      Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest()     1024      
  #3      Symfony\Component\HttpKernel\EventListener\DumpListener::configure()               1024      
  #4      Mea\Crm4Bundle\Listener\CrmApplicationRequestListener::onKernelRequestInit()       255       
  #5      Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest()    128       
  #6      Symfony\Component\HttpKernel\EventListener\FragmentListener::onKernelRequest()     48        
  #7      Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest()       32        
  #8      Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest()       16        
  #9      FOS\RestBundle\EventListener\BodyListener::onKernelRequest()                       10        
  #10     Symfony\Component\HttpKernel\EventListener\TranslatorListener::onKernelRequest()   10        
  #11     Symfony\Component\Security\Http\Firewall::onKernelRequest()                        8         
  #12     Mea\Crm4Bundle\Listener\CrmApplicationRequestListener::onKernelRequest()           0         
  #13     Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest()      0         
 ------- ---------------------------------------------------------------------------------- ---------- 

在 CrmApplicationRequestListener::onKernelRequestInit 中

我设置了 onKernelRequestInit,它现在可见。

但我仍然需要更改路由默认值:{ _applicationid: 0 }

symfony 生成的每条路径都有默认的_applicationid: 0 不是监听器中设置的当前真实_applicationid。 不可能为每个路由添加当前的 _applicationid。我必须更改路由器中的默认值。我希望这个问题现在已经清楚了。

更新 4 我也尝试创建自定义路由加载器 - 这是问题 symfony2 add dynamic parameter for routing, try with custom loader

最佳答案

您的问题不是很清楚,但您可能需要检查您的监听器优先级是否已设置,以便它在路由器监听器之前运行。


编辑:

假设您没有尝试使用 path() 在您的 twig View 中设置 _applicationid 的值——例如{{ path('path_name', {'_applicationid': 2}) }} – 这将起作用,并且可能是更好的选择 – 您仍然应该能够使用监听器设置它。

在检查了 Symfony 自己的 LocaleListener 之后,我能够使用语句 $this- 将 _applicationid 的值设置为 2 >router->getContext()->setParameter('_applicationid', 2);.订阅者的优先级似乎没有任何区别,但在 View 中设置值优先于监听器。

框架路由:

# app/config/routing.yml
acme_test:
    resource: "@AcmeTestBundle/Resources/config/routing.yml"
    prefix:   /{_applicationid}
    defaults:
        _applicationid: 0
    requirements:
        _applicationid: 0|1|2|3|4

捆绑路由:

# src/Acme/TestBundle/Resources/config/routing.yml
acme_test_home:
    path:     /
    defaults: { _controller: AcmeTestBundle:Default:index }

服务定义:

# src/Acme/TestBundle/Resources/config/services.yml
services:
    acme_test.listener.app_id_listener:
        class: Acme\TestBundle\EventListener\AppIdListener
        arguments:
            - "@router"
        tags:
            - { name: kernel.event_subscriber }  

订阅者:

# src/Acme/TestBundle/EventListener/AppIdListener.php
namespace Acme\TestBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AppIdListener implements EventSubscriberInterface
{
    private $router;

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

    public function onKernelRequest(GetResponseEvent $event)
    {
        $this->router->getContext()->setParameter('_applicationid', 2);
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
        );
    }
}

关于php - Symfony2 - 如何为每个请求或生成的 URL 的路由添加一个全局参数,类似于 _locale?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223693/

有关php - Symfony2 - 如何为每个请求或生成的 URL 的路由添加一个全局参数,类似于 _locale?的更多相关文章

  1. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  2. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  3. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  4. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  5. ruby - 如何为 emacs 安装 ruby​​-mode - 2

    我刚刚为fedora安装了emacs。我想用emacs编写ruby。为ruby​​提供代码提示、代码完成类型功能所需的工具、扩展是什么? 最佳答案 ruby-mode已经包含在Emacs23之后的版本中。不过,它也可以通过ELPA获得。您可能感兴趣的其他一些事情是集成RVM、feature-mode(Cucumber)、rspec-mode、ruby-electric、inf-ruby、rinari(用于Rails)等。这是我当前用于Ruby开发的Emacs配置:https://github.com/citizen428/emacs

  6. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  7. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

  8. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  9. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

  10. ruby-on-rails - Rails - 从另一个模型中创建一个模型的实例 - 2

    我有一个正在构建的应用程序,我需要一个模型来创建另一个模型的实例。我希望每辆车都有4个轮胎。汽车模型classCar轮胎模型classTire但是,在make_tires内部有一个错误,如果我为Tire尝试它,则没有用于创建或新建的activerecord方法。当我检查轮胎时,它没有这些方法。我该如何补救?错误是这样的:未定义的方法'create'forActiveRecord::AttributeMethods::Serialization::Tire::Module我测试了两个环境:测试和开发,它们都因相同的错误而失败。 最佳答案

随机推荐