views:

40

answers:

2

In PHP I often do the following:

$_SESSION['var']['foo'] = array('bar1' => 1, 'bar2' => 2);
// ...
$_SESSION['var']['foo']['bar2'] = 3;
// ...
echo $_SESSION['var']['foo']['bar2']; // 3

I'm wondering what the recommended way of storing multidimensional arrays in a session with Kohana.

I know I can do the following, but I don't know how to make it work with multidimensional, specifically the get portion:

Session::instance()->set('var', array(
 'foo' => array(
  'bar1' => 1,
  'bar2' => 2,
 ),
));
// ...
// how do I set just bar2?
// ...
// this gets the whole array, but how do I get just bar2? 
Session::instance()->get('var');

So, the questions are:

  1. How do I set just bar2?
  2. How do I get just bar2?

Is there a way to do either of these in Kohana 3?

I'd love to use the native sessions, but we are trying to use database sessions.

+3  A: 

The short answer is that there is no way to do that, given the current implementation of Kohana sessions. You have two alternatives:

Either get and set the entire array, editing the bits you need each time:

$array = Session::instance()->get('var');
$array['foo']['bar2'] = 'baz';
Session::instance()->set('var', $array);

Or you override the Kohana_Session->get() and ->set() methods (which are defined here on github). Keep in mind that, given the wonderful "layered" filesystem in Kohana, you can actually extend the class, modifying just the method you need, without editing the core Kohana code.

My idea would be to change the $key parameter to accept either strings or arrays. If you pass in an array, it should interpret each element in the array as a "deeper" level.

$key = array('var', 'foo', 'bar2');
Session::instance()->get($key, $default);
Session::instance()->set($key, 'baz');
MartinodF
I was also thinking of your second option...just need to figure out how to implement it.
Darryl Hein
A: 
$session = & Session::instance()->as_array();
$session['foo']['bar2'] = 'baz';

UPD. Also, you can use Arr::path():

$bar2 = arr::path(Session::instance()->as_array(), 'foo.bar2');// returns 'baz'
$bars = arr::path(Session::instance()->as_array(), '*.bar2');  // returns array of bar2's
biakaveron