Domanda

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.

thank you in advance

È stato utile?

Soluzione

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

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

to retrieve this:

$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
// )

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

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

Altri suggerimenti

Session::set('checked', true);
$isChecked = Session::get('checked');

This should get you started.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top