Zend Framework 2 - Cookie 概念 [英] Zend Framework 2 - Cookie Concept

查看:32
本文介绍了Zend Framework 2 - Cookie 概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我冲浪了很多.我想使用 COOKIE 分配和检索一个值.我在 ZF2 怎么办?我看到了很多在 cookie 中赋值的例子.请解释如何从 cookie 中检索值.

I have surfed a lot. I would like to assign and retrieve a value using a COOKIE. How can i do in ZF2? I saw a lot of examples for assigning value in cookie. Please explain that how to retrieve a value from cookie.

推荐答案

HTTP 中的 cookie(参见 RFC 2109 只是存储在请求中的内容,并在每次发出请求时发送.响应可以添加其他参数以额外存储到现有的 cookie 中.

A cookie in HTTP (see RFC 2109 simply something stored in the request and send every time a request is made. A response can add other parameters to be stored additionally to the already existing cookies.

因此cookie检索是通过Request完成的,以更新您使用Response的cookie.根据 RFC 2109,您分别使用 Cookie 标头和 Set-Cookie 标头.因此,您可以通过

So the cookie retrieval is done via the Request, to update a cookie you use the Response. According to RFC 2109 you use respectively the Cookie header and the Set-Cookie header. You can thus directly access these headers via

$this->getRequest()->getHeaders()->get('Cookie')->foo = 'bar';

或通过以下方式设置 cookie:

Or set cookies via:

$this->getResponse()->getHeaders()->get('Set-Cookie')->foo = 'bar';

事情变得简单了一点,因为在请求和响应中有一个代理可以直接访问 cookie:

Things are made a little bit easier though because there is a proxy at the request and response to directly access the cookie:

public function fooAction()
{
  $param = $this->getRequest()->getCookie()->bar;

  $this->getResponse()->getCookie()->baz = 'bat';
}

请记住 CookieSet-Cookie 标头实现了 ArrayObject 对象.要检查请求中是否存在 cookie,您可以使用 offsetExists:

Keep in mind the Cookie and Set-Cookie headers implement the ArrayObject object. To check whether a cookie is present in the request, you can thus use offsetExists:

if ($cookie->offsetExists('foo')) {
    $param = $cookie->offsetGet('foo');
}

/更新:

如果您想修改 cookie 的属性,您也可以在这里修改 Set-Cookie 标头.看看 Github 上的课程 所有可用的方法.

If you want to modify properties of the cookie, you are also here modifying the Set-Cookie header. Take a look at the class on Github for all the methods available.

小总结:

$cookie = $this->getResponse()->getCookie();
$cookie->foo = 'bar';
$cookie->baz = 'bat';

$this->setDomain('www.example.com');
$this->setExpires(time()+60*60*24*30);

这篇关于Zend Framework 2 - Cookie 概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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