如何在 Silex 中设置和获取饼干


How do you set and get cookies in Silex?

正如标题所暗示的,

这是代码...

public function index(Request $request, Application $app)
{
    $cookies = $request->cookies;
    print_r($request->cookies);
    if(!$cookies->has("recordsPerPage"))
    {
        $response = new Response();
        $cookie = new Cookie("recordsPerPage", $app['defaultRecordsPerPage']);
        $response->headers->setCookie($cookie); 
    }
    print_r($request->cookies);exit; //prints nothing here !!
}

我也试图在$app->after()中设置它,但失败了。 除了在控制器中之外,您还有其他方法可以设置 cookie 吗?

谢谢。

Cookie 设置有响应,并在下次请求时可用。因此,您必须使用此cookie返回响应,如果您希望它在请求中可用,请将其设置为重定向响应,以便浏览器将设置cookie并使用此新创建的cookie发出下一个请求:

$cookies = $request->cookies;
if(!$cookies->has("recordsPerPage"))
{
    $cookie = new Cookie("recordsPerPage", $app['defaultRecordsPerPage']);
    $response = Response::create('', 302, array("Location" => "http://127.0.0.1/whatever/"));
    $response->headers->setCookie($cookie);
    return $response;
}else{
    return print_r($cookies, 1);
}

另一种可能性是直接在请求中设置此cookie($request->cookies->set('recordsPerPage', $app['defaultRecordsPerPage']);),但您仍然必须使用此cookie返回响应才能在浏览器中进行设置。