Symfony2:如何将url查询字符串参数传递给控制器​​? [英] Symfony2: How to pass url querystring parameters to controllers?

查看:91
本文介绍了Symfony2:如何将url查询字符串参数传递给控制器​​?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我遗漏了一些东西,但是似乎没有一种方法可以在Symfony2的路由中定义查询字符串参数,以便可以将它们传递到控制器中.

Maybe I am missing something but there doesn't seem to be a way to define querystring parameters in routes in Symfony2 so that they can be passed into a controller.

例如,而不是生成类似/blog/my-blog-post的URI(来自Symfony2的路由文档),并且将其传递到以下路线:

For instance, instead of generating a URI like /blog/my-blog-post (from Symfony2's routing documentation) and passing it to the following route:

# app/config/routing.yml    
blog_show:
    pattern:   /blog/{slug}
    defaults:  { _controller: AcmeBlogBundle:Blog:show }

我希望生成一个/blog?slug=my-blog-post之类的URI.问题是我找不到在路由配置文件中定义slug参数的地方(就像上面的{slug}对应物一样).

I would prefer to generate a URI like /blog?slug=my-blog-post. The problem is I can't find anywhere to define the slug parameter in the route configuration file (like its {slug} counterpart above).

也许这是故意的,但是在查询字符串中使用GET参数的最佳实践是什么?

Perhaps this is on purpose but then what is the best practice for working with GET parameters in the querystring?

该文档的确在使用查询字符串生成URL中进行了提及,那么如何将它们传递给控制器​​?

The documentation does make mention of them in Generating URLs with Query Strings, so how to pass them into the controller?

我可以在其中找到提及它们的地方是 Symfony2和HTTP基础知识:

Where I can find mention of them is Symfony2 and HTTP Fundamentals:

use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();

// retrieve GET variables
$request->query->get('foo');

这是在控制器内部使用它们的最佳实践吗?

Is this the best practice for working with them inside the controller?

推荐答案

要在扩展Symfony \ Bundle \ FrameworkBundle \ Controller \ Controller的控制器中使用GET/POST参数:

To work with GET / POST parameters in a controller that extends Symfony\Bundle\FrameworkBundle\Controller\Controller:

public function updateAction()
{
    $request = $this->getRequest();
    $request->query->get('myParam'); // get a $_GET parameter
    $request->request->get('myParam'); // get a $_POST parameter
    ...
}

对于不扩展Symfony基本控制器的控制器,请将请求对象声明为action方法的参数,然后按上述步骤进行操作:

For a controller which does not extend the Symfony base controller, declare the request object as a parameter of the action method and proceed as above:

public function updateAction(Request $request)
{
    $request->query->get('myParam'); // get a $_GET parameter
    $request->request->get('myParam'); // get a $_POST parameter
    ...
}

这篇关于Symfony2:如何将url查询字符串参数传递给控制器​​?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆