Storing Session Data

给你一囗甜甜゛ 提交于 2019-12-11 12:43:39

问题


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

Or as an Array:

// The Second Example
$this->getUser()->setAttribute('something'
    , array('hash' => $hash,'name' => $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?


回答1:


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

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



来源:https://stackoverflow.com/questions/7493636/storing-session-data

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