2

我知道有人讨论了在 Symfony2 中处理路由的最佳实践(routing.yml vs annotations)。让我提一下,我想使用注释保持原样。

当我在控制器中为单个操作定义多个路由时,@Method注释的最后一个定义似乎覆盖了所有其他的,这就是为什么我收到以下错误:

No route found for "POST /index": Method Not Allowed (Allow: GET, HEAD)

这只是我正在使用的一小段代码。

namespace MySelf\MyBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class MyController extends Controller{

    /**
     * @Route(
     *     "/index",
     *     name="index_default"
     * )
     * @Method({"GET", "POST"})
     *
     * @Route(
     *     "/index/{id}",
     *     name="index",
     *     requirements={
     *          "id": "\d+"
     *     }
     * )
     * @Method({"GET"})
     *
     * @return Response
     */
     public function indexAction($id = null){
          /*DO SOME FANCY STUFF*/
          ...
          return $response;
     }
}

虽然这工作得很好!

index_default:
    pattern: /index
    defaults: { _controller: MyBundle:MyController:index }
    requirements:
      _method: GET|POST

index:
    pattern: /index/{id}
    defaults: { _controller: MyBundle:MyController:index }
    requirements:
      _method: GET
      id: \d+

有什么想法可以使用注释来实现它与 routing.yml 一起使用的方式吗?

4

2 回答 2

4

您应该在每个路由注释中指定方法,@Method 只能声明一次。事实上,每种类型的注释都是单独处理的,它们彼此不知道。

/**
 * @Route(
 *     "/index",
 *     name="index_default",
 *     methods="GET|POST"
 * )
 *
 * @Route(
 *     "/index/{id}",
 *     name="index",
 *     requirements={
 *          "id": "\d+"
 *     },
 *     methods="GET"
 * )
 *
 * @return Response
 */
于 2015-04-17T14:56:28.220 回答
0

我认为不可能两次声明@route 或@Method 注释。您可以像这样为 $id 创建一个默认值:

/**
 * @Route(
 *     "/index/{id}",
 *     name="index",
 *     requirements={
 *          "id": "\d+"
 *     },
 *     defaults={"id" = null}
 * )
 *
 * @Method({"GET", "POST"})
 *
 * @return Response
 */
public function indexAction($id)
{
    /*DO SOME FANCY STUFF*/
      ...
      return $response;
}

[编辑] 好的,实际上可以在注解中声明多个路由。但是,我认为您不应该再次声明 @Method 。我不确定这一点,但似乎是这样的:

@Method({"GET"})

覆盖此:

@Method({"GET", "POST"})

当你覆盖它时,你只剩下 GET 了。删除仅声明 GET 的注释,它应该可以工作。

于 2015-04-17T12:45:56.567 回答