SilverStripe - 会话使用的简单示例 [英] SilverStripe - Simple example of session usage

查看:46
本文介绍了SilverStripe - 会话使用的简单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从会话开始,但直到现在(是的,我对文档进行了红色标记)我完全不知道如何开始.

i'm trying to start with session, but until now (yes I red the docs) I absolutely don't know how to start.

也许有人可以给我举个简单的例子.例如.存储是否选中复选框.

perhaps someone can give me a simple example. E.g. store if a checkbox is checked or not.

先谢谢你

推荐答案

SilverStripe 会议非常简单.Session 类只是 php $_SESSION

SilverStripe sessions are pretty straight forward. the class Session is just a nice wrapper around the php $_SESSION

Session::set('MyCheckboxValue', 'Hello World');

要检索这个:

$value = Session::get('MyCheckboxValue');
// note this will always return something, even if 'MyCheckboxValue' has never been set.
// so you should check that there is a value
if ($value) { ... }

还有一些处理数组的逻辑:

there also is some logic in there to work with arrays:

Session::set('MyArray', array('Bar' => 'Foo', 'Foo' => 'yay'));
// this will add the string 'something' to the end of the array
Session::add_to_array('MyArray', 'something');
// this will set the value of 'Foo' in the array to the string blub
// the . syntax is used here to indicate the nesting.
Session::set('MyArray.Foo', 'blub');
Session::set('MyArray.AnotherFoo', 'blub2');

// now, lets take a look at whats inside:
print_r(Session::get('MyArray'));
// Array
// (
//     [Bar] => Foo
//     [Foo] => blub
//     [0] => something
//     [AnotherFoo] => blub2
// )

<小时>

您还应该注意的一件事是 Session::set() 不会立即保存到 $_SESSION 中.这是在处理请求结束时完成的.此外 Session::get() 不直接访问 $_SESSION,它使用缓存数组.所以下面的代码会失败:


one thing you should also be aware of is that Session::set() does not save into $_SESSION right away. That is done at the end of handling the request. Also Session::get() does not directly access $_SESSION, it uses a cached array. So the following code will fail:

Session::set('Foo', 'Bar');
echo $_SESSION['Foo']; // this will ERROR because $_SESSION['Foo'] is not set.
echo Session::get('Foo'); // this will WORK

这也意味着如果您使用 die() 或 exit(),会话将不会被保存.

this also means if you use die() or exit(), the session will not be saved.

Session::set('Foo', 'Bar');
die(); // because we die here, this means SilverStripe never gets a clean exit, so it will NEVER save the Session

.

Session::set('Foo', 'Bar');
Session::save();
die(); // this will work because we saved

这篇关于SilverStripe - 会话使用的简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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