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

查看:17
本文介绍了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?

文档确实在 Generating URLs with Query Strings 中提到了它们,那么如何将它们传递给控制器​​呢?

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 SymfonyComponentHttpFoundationRequest;

$request = Request::createFromGlobals();

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

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

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

推荐答案

在扩展 SymfonyBundleFrameworkBundleControllerController 的控制器中使用 GET/POST 参数:

To work with GET / POST parameters in a controller that extends SymfonyBundleFrameworkBundleControllerController:

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天全站免登陆