Attaching a cookie to a view in Symfony2

99封情书 提交于 2020-01-22 12:41:31

问题


I've found a few questions and pages dealing with cookies in Symfony2 but there doesn't seem to be any clear consensus on exactly how this is supposed to work. I can, of course, just fall back to using PHP's native setcookie function but I feel that it should be an easy thing to do with Symfony2 as well.

I have an action in my controller from which I simply want to return a view with a cookie attached. Thus far I have seem examples basically like this:

use Symfony\Compentnt\HttpFoundation\Response;

public function indexAction() {
  $response = new Response();
  $response->headers->setCookie(new Cookie('name', 'value', 0, '/');
  $response->send();
}

The problem with this is that it sends the response... and doesn't render the view. If I set the cookie without sending the headers the view is rendered but the header (cookie) is not sent.

Poking around I found the sendHeaders() method in the Response object so I'm now manually calling that in my action before returning and that seems to work:

public function indexAction() {
  ...
  $response->sendHeaders();
  return array('variables' => 'values');
}

But is this really the expected pattern to use? In previous versions of symfony I could set the headers in my controller and expect the view controller to handle sending whatever I had sent. It seems now that I must manually send them from the action to get it to work, meaning I have to call this from any action that I set headers in. Is this the case or is there something that I'm missing that's so obvious that no one has bothered to even mention it in any of the documentation?


回答1:


I think you're on the right lines with:

$response->headers->setCookie(new Cookie('name', 'value', 0, '/'));

If you're trying to render a template then check out the docs here:

Symfony2 Templating Service

If you look at the line:

return $this->render('AcmeArticleBundle:Article:index.html.twig');

basically the render method is returning a response (which the controller then returns) which has the content of the twig template, all you have to do is intercept this:

$response = $this->render('AcmeArticleBundle:Article:index.html.twig');
$response->headers->setCookie(new Cookie('name', 'value', 0, '/'));
return $response;

I think that's it anyway...



来源:https://stackoverflow.com/questions/7919706/attaching-a-cookie-to-a-view-in-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!