如何在 Symfony2 中解析 get url


// route
TestTestAppBundle_foobar:
    pattern:  /foobar
    defaults: { _controller: TestTestAppBundle:Default:fooar }

//controller
public function foobarAction(Request $request)
    {
        $request = $this->getRequest();
        $method = $request->getMethod();
        $var =  $request->query->keys();
        $response = new Response('Content', 200, array('content-type' => 'text/html'));
        $response->setContent($var);
        return $response;
    }

当我调用 URL 时

/foobar?foo=bar

然后它返回空数组。相反,它应该返回 GET 参数。

如何在symfony中处理GET请求?

尝试在pattern中添加斜杠,例如

pattern:  /foobar/

它还将确保路由与/foobar/foobar/模式相匹配。

它永远不会像这样工作,原因有两个:

  • 据我所知,它正在获取查询字符串,但setContent有点混乱。第一个参数不应该是数组,而是字符串。因此,$var[0]将起作用并将内容设置为foo

  • 此外,您的路由有点错误。您的模式/foobar,但您正在尝试打开/foobar/这是不一样的。如果设置pattern: /foobar/,则可以同时使用 /foobar//foobar(实际上重定向到 /foobar/ )。

但是,query->keys()在这种情况下,这将只返回键。如果要同时获取键和值,则应仅对foo值使用 query->all()query->get('foo')

此外,您不需要使用 $request = $this->getRequest();因为请求已经是您操作中的第一个参数。您可以直接使用它。

在这种情况下,setContent也有点无用,因为Response的第一个参数已经调用了它,因此您可以在不使用额外函数调用的情况下将其设置在那里。

最新更新