nTO*_*XIC 3 php annotations controller http-protocols symfony
我知道有人讨论 Symfony2 中处理路由的最佳实践(routing.yml 与注释)。让我提一下,我想保持原样,使用注释。
当我在控制器中为单个操作定义多个路由时,注释的最后一个定义似乎@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;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然这工作得很好!
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+
Run Code Online (Sandbox Code Playgroud)
是否有想法以使用注释的方式使用routing.yml 来实现它?
您应该在每个路由注释中指定方法,@Method 只能声明一次。事实上,每种类型的注释都是单独处理的,它们彼此不知道。
/**
* @Route(
* "/index",
* name="index_default",
* methods="GET|POST"
* )
*
* @Route(
* "/index/{id}",
* name="index",
* requirements={
* "id": "\d+"
* },
* methods="GET"
* )
*
* @return Response
*/
Run Code Online (Sandbox Code Playgroud)