[K4] Session: new syntax or bug?


Has anything changed in the use of the Session class in Kirby 4?

I’m asking because I’m getting the following error message:

Uncaught Exception: Serialization of ‘Closure’ is not allowed in /home/…/kirby/src/Session/Session.php:372

when I try to set a value in session:

$session = $kirby->session(); $session->set('test', $page->title());

I’ve tested this two lines in the template/default.php file of the plainkit and get the same error.
The error don’t display on the web page when Kirby debug mode is on, I saw this error in my terminal when php -S localhost:8001 kirby/router.php is running.

the field is probably not cast to a string because of some more strict typing. try adding a cast or use the ->value() method to verify.

Yep, thanks Bruno, the error message disappear if I write $session->set('test', $page->title()->value());

But what if I want to set a collection of pages? $session->set('test', $site->children()->unlisted());
The same error occurs.

I guess you will have to serialize the collection yourself:

use Kirby\Cms\Pages;
use Kirby\Toolkit\A;

// to store pages in session:
$session->set('test',  $site->children()->unlisted()->values(
  fn($p) => $p->uuid()->toString()

// later, to get the pages out of the session:
$pagesInSession = new Pages(
  A::map($session->get('test', []), kirby()->page(...))

Ouch, it just got a lot more complicated :thinking:
Thanks for your answer

Was this documented anywhere in Kirby’s documentation?

I don’t actually know if the team knows about this.
The changelog for v4 doesn’t mention related changes to session or serialize.
Maybe really it’s an undocumented breaking change, I mean it’s actually rather curious because neither Pages, nor Field is a really “Closure”. I don’t know what triggers the error or what part of those classes contain closures, the only Closures that come to mind are the fieldmethods, but those were already present in v3 and are anyway static (so they shouldn’t be serialized).
Maybe they now contain some instances of the LazyValue class which actually stores a closure as instance data…

I guess putting pages or fields into a session isn’t very common, so there probably isn’t a test for this.
I would still mention this as regression on Github. If it’s intended behaviour, they can always close the issue.

Done: [K4] Session: need to serialize data. Regression? · Issue #6061 · getkirby/kirby · GitHub