在Symfony中配置一个URL相同但HTTP方法和控制器动作不同的路由


Configuring a route in Symfony with the same URL but different HTTP methods and controller actions

我在Symfony应用程序中配置了以下路由:

label:
  url:          /label
  param:        { module: label, action: configure }
  requirements: { sf_method: get }
label_create:
  url:          /label
  param:        { module: label, action: create }
  requirements: { sf_method: post }

executeConfigureexecuteCreate作用相关。然后我有一个这样配置的表单:

<form action="<?php echo url_for('@label_create') ?>" method="POST">
  <?php echo $form->renderHiddenFields() ?>
  <input type="hidden" name="sf_method" value="post" />
  <!-- more stuff here -->
</form>

每当提交表单时,执行executeConfigure,尽管据我所知,使用POST方法配置的路由应该避免执行executeCreate

我如何区分这两个操作保持相同的URL?

谢谢!

我也有这个问题,并在一个旧的论坛消息(http://oldforum.symfony-project.org/index.php/t/25750/)中找到了答案。

如果它完全忽略请求方法,那么它很可能使用常规的路由。你需要使用sfRequestRoute来使路由"方法感知"。因此,在您的示例中,您将执行:

label:
  url:          /label
  class:        sfRequestRoute
  param:        { module: label, action: configure }
  requirements: { sf_method: get }
label_create:
  url:          /label
  class:        sfRequestRoute
  param:        { module: label, action: create }
  requirements: { sf_method: post }

我通过使用以下路由方案解决了这个问题:

users_create:
    pattern:     /
    defaults: { _controller: "RentalAPIBundle:User:create" }
    requirements: { _method: post }
users:    
    pattern:     /    
    defaults: { _controller: "RentalAPIBundle:User:index" }    
    requirements: { _method: get }

则在调用Url时,对于GET,您可以调用user或user/,但对于POST,只能调用users/。我不知道为什么,但它确实有效