我在Controller操作中设置了一些cookie,然后在另一个操作中我想要读取cookie集并使用该值执行某些操作。但是,在尝试读取cookie时,我看到的只是一个空数组,我的代码如下:
public function testSetCookieAction()
{
$value = 'ABCDEFGHI'
$cookie = new Cookie('SYMFONY2_TEST', $value, (time() + 3600 * 24 * 7), '/');
$response = new Response();
$response->headers->setCookie($cookie);
$response->send();
.
.
.
}
public function testReadCookieAction()
{
$response = new Response();
$cookies = $response->headers->getCookies();
// $cookies = array(0) { }
}
当我var_dump($_COOKIE);
时,我看到array(1) { ["SYMFONY2_TEST"]=> string(9) "ABCDEFGHI" }
有人知道我做错了吗?
提前致谢
答案 0 :(得分:50)
您必须阅读Request对象上的cookie,而不是刚刚创建的void Response对象;)
public function testReadCookieAction(Request $request)
{
$cookies = $request->cookies;
if ($cookies->has('SYMFONY2_TEST'))
{
var_dump($cookies->get('SYMFONY2_TEST'));
}
}