将Cookie附加到Symfony2中的视图 [英] Attaching a cookie to a view in Symfony2

查看:85
本文介绍了将Cookie附加到Symfony2中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Symfony2中发现了一些有关Cookie的问题和页面,但对于确切的工作方式似乎没有明确的共识。当然,我可以回过头来使用PHP的本机 setcookie 函数,但是我觉得使用Symfony2也是一件容易的事。

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.

我在控制器中有一个动作,我只想从中返回一个带有cookie的视图。到目前为止,我似乎已经看到了基本上这样的示例:

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();
}

此问题是它发送响应...并且不呈现视图如果我没有发送标题就设置了cookie,则呈现视图,但不发送标题(cookie)。

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.

四处寻找,我发现了 Response对象中的sendHeaders()方法,所以我现在在返回之前在操作中手动调用它,这似乎可行:

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');
}

但这真的是预期使用的模式吗? symfony我可以在控制器中设置标头,并期望视图控制器处理发送的内容,现在看来我必须从动作中手动发送它们才能使其正常工作,mea宁我必须从设置标头的任何操作中调用它。是这种情况还是缺少的东西如此明显,以至于没人在任何文档中都提到它?

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?

推荐答案

我认为您的选择正确:

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

如果您要渲染模板,请在此处查看文档:

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

Symfony2模板服务

如果您查看以下行:

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

基本上,render方法返回一个响应(控制器随后返回),该响应具有树枝模板,您所需要做的就是拦截它:

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...

这篇关于将Cookie附加到Symfony2中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆