WebTestCase、Silex 和 $_GET

WebTestCase, Silex and $_GET

我在使用 Silex 的 WebTestCase 上遇到了一些问题:在我的控制器的一个动作中,我需要一个通过普通 $_GET 传递的参数(我必须这样做,因为它是一个 URL,Apache 解释%2F 如果它在查询字符串之外——参见 Url Variables with %2f not handled by silex 例如)

我的路线是这样定义的:

$controller
   ->get('/get', <controller action>)
   ->value('url', (!empty($_GET['url']) ? $_GET['url'] : false));

它在浏览器中运行良好,但它似乎无法在像这样的 WebTestCase 中运行:$_GET 保持为空...

$client = $this->createClient();
$client->request('GET', '/get?url=' . urlencode($url));

编辑

我刚刚做了一个快速实验:如果我在我的路线中执行以下操作:

$controller
        ->get('/get/{url}', <action>)
        ->assert('url', '.*');

而这个在测试中:

$client = $this->createClient();
$client->request('GET', '/get/' . urlencode($url));

如果一切正常,$url 将传递给控制器​​...但是,它在通过 Apache 传递时不再在浏览器上工作。

服务器全局变量(如 $_GET)由 Apache 填充。当 运行 功能测试时,Apache 被跳过,因此不再填充 $_GET。您应该使用 Request 对象来提取 GET 参数,而不是使用服务器全局变量。这样,框架将同时拦截 PHPUnit 注入变量和 Apache 注入变量;然后它将通过可以作为函数参数注入的 Request 对象使它们在您的操作方法中可用。

如何提取 url 参数的示例:

$url = $request->query->get('url');