存储会话数据 [英] Storing Session Data

查看:24
本文介绍了存储会话数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些关于在 Symfony 中存储会话数据的反问.我们可以将会话数据存储为变量:

I have some rhetorical question regarding storing session data in Symfony. We can store session data as variables:

// The First Example
$this->getUser()->setAttribute('hash', $hash);
$this->getUser()->setAttribute('name', $name);

或者作为数组:

// The Second Example
$this->getUser()->setAttribute('something'
    , array('hash' => $hash,'name' => $name));

对于第一个示例,我们可以使用 hasAttribute('name') 来检查它是否已设置,对于第二个示例,我们将需要两行代码来进行此类检查.例如.像 hasAttribute('name') 这样的方法将不起作用:

With the first example, we can use hasAttribute('name') to check if it's set and with the second example, we will need two lines of code for such check. E.g. Methods like hasAttribute('name') will not work:

$something = $this->getUser()->getAttribute('something');
if($something['name']) //...

此外,为变量设置新值需要更多行:

Also, setting new value to variable requires more lines:

$something['name'] = 'New value';
$this->getUser()->setAttribute('something', $something);

但是使用数组来存储会话的好处是能够一次清除整个数组.

But the benefit of having an Arrays for to store sessions is the ability to clear the whole Array at once.

也许有可能以我不知道的更好的方式操作数组?或者也许我的陈述完全错了......最佳做法是什么?

Maybe it's possible to manipulate Arrays the better way which I'm not aware of? Or maybe I'm wrong with my statements at all... What is the best practice?

推荐答案

您可以添加命名空间来存储您的数据:

You can add a namespace to store your data:

$this->getUser()->setAttribute($name, $value, $namespace);

为了检索数据,您还需要使用命名空间:

And to retrieve the data, you need to use the namespace as well:

$this->getUser()->getAtrribute($name, $default, $namespace);

并且您可以检查用户是否也具有带有名称空间的属性:

And you can check the if the user has an attribute with a name space as well:

$this->getUser()->hasAttribute($name, $namespace);

symfony 会将值作为数组存储到命名空间中.

And symfony will store the values into the namespace as an array.

这篇关于存储会话数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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