如何使用 Symfony 2 将数组作为参数传递给 Controller 操作?您能否写一个如何定义路由的示例,其中包含未知长度的数组作为参数。例如网址:http://localhost:8000/blog/post/?tags=[tag1,tag2,tag3]其中标签数量从 0 到 100 不等。 还有此路由的示例 Controller ,其中操作返回标签数组的值。
使用以下编码(请参阅下面的routing.yml和controller.php)我收到错误:
Catchable Fatal Error: Argument 3 passed to Symfony\Component\Routing\Route::__construct() must be of the type array, string given, called in C:\Bitnami\wampstack-5.5.30-0\sym_prog\dctr\vendor\symfony\symfony\src\Symfony\Component\Routing\Loader\YamlFileLoader.php on line 147 and defined in C:\Bitnami\wampstack-5.5.30-0\sym_prog\dctr\app/config\routing.yml (which is being imported from "C:\Bitnami\wampstack-5.5.30-0\sym_prog\dctr\app/config/routing_dev.yml").
网址:
http://localhost:8000/blog/post/tag1
http://localhost:8000/blog/post/tag1/tag2/tag3/tag4
http://localhost:8000/blog/post/?tags=[tag1,tag2]
以下是我迄今为止尝试过的路由和 Controller 文件的不同组合:
//版本r1,路由.yml
blog_post_tags:
path: blog/post/{tags}
defaults: { _controller: DefaultController:list_postsByTagActionQ }
requirements:
tags : "[a-zA-Z0-9,]+"
//版本r2,路由.yml
blog_post_tags:
resource: "@BlogBundle/Controller/"
type: annotation
prefix: /blog/
defaults: { _controller: DefaultController:list_postsByTagActionQ }
//版本r1,2-c1,controller.php
//http://localhost:8000/blog/post/?tags=[tag1,tag2] .
/**
* @Route("/posts/{tags}")
* @Template()
*/
public function list_postsByTagAction($tags){
var_dump($tags);
return array('posts'=>['post1','post2']);
}
//版本r1,2-c2,controller.php
//url http://localhost:8000/blog/post/?tags=[tag1,tag2]
/**
* @Route("/posts/{tags}")
* @Method("GET")
* @Template()
*/
public function list_postsByTagActionQ1(Request $request){
$tags=$request->query->get('tags'); // get a $_GET parameter
var_dump($tags);
return array('posts'=>['post1','post2']);
}
//版本r1,2-c3,controller.php
//url http://localhost:8000/blog/post/?tags=[tag1,tag2]
/**
* @Route("/posts/{tags}")
* @Method("GET")
* @Template()
*/
public function list_postsByTagActionQ3(Request $request, $tags){
var_dump($tags);
return array('posts'=>['post1','post2']);
}
//版本r3,路由.yml
blog_post_tags:
path: blog/post/{tags}
defaults: { _controller: DefaultController:list_postsByTagActionQ }
//版本r3-c4,controller.php
//url http://localhost:8000/blog/post/?tags=[tag1,tag2]
public function list_postsByTagActionQ(Request $request){
$tags=$request->query->get('tags'); // get a $_GET parameter
var_dump($tags);
}
最佳答案
好吧,经过一番尝试,我找到了下一个解决方案。
您可以更改路由模式(标签:“[a-zA-Z0-9/]+”):
blog_post_tag:
path: blog/post/{tags}
defaults: { _controller: DefaultController:list_postsByTagActionQ }
requirements:
tags : "[a-zA-Z0-9\/]+"
然后你可以通过http://localhost:8000/blog/post/tag1/tag2/tag3/tag4 ,但是你仍然需要explode()来获取参数。
关于Symfony2,如何将数组作为参数传递给 Controller 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33595604/