Symfony2:读取带有Request对象的Cookie不起作用


Symfony2: Reading a Cookie with Request object not working

当我创建一个cookie时,$response对象可以完美地读取它,但当刷新页面时,我会得到空数组。在谷歌上搜索了一些例子,发现它必须使用请求对象,但根本不起作用。你知道我遗漏了什么吗?

public function indexAction(Request $request) {
    $response = new Response();
    var_dump($response->headers->getCookies()); //GIVES EMPTY ARRAY
    var_dump($request->cookies->all()); //GIVES ONLY PHPSESSID, BUT NOT THE ONE CREATED
    var_dump($request->cookies->get('user')); //GIVES NULL
    // ... //
    if ($loginForm->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $dql = // ... //                    ));
        $result = $dql->getArrayResult();
        if ($result) {
            foreach ($result as $profile) {
                $cookie = // ... //
                $response->headers->setCookie(new Cookie('user', $cookie, $expire = 0, $path = '/', $domain = 'null', $secure = false, $httpOnly = false));
                $response->sendHeaders();
            }
            var_dump($response->headers->getCookies()); //GIVES CORRECT COOKIE OBJECT
            var_dump($request->cookies->all()); //GIVES ONLY PHPSESSID, BUT NOT THE ONE CREATED
            var_dump($request->cookies->get('user')); //GIVES NULL
        }

您将域设置为"null"(字符串),因此当您尝试读取它时,它不会显示,因为您不在"null"域下。如果你想使用默认值,它应该只是null(而不是字符串)。