I can't get my Symfony 5.2 session bag working with native file handling. Here is my bag...
class TestSessionBag extends AttributeBag implements SessionBagInterface
{
public const NAME = 'TestSessionBag';
public function __construct() {
}
public function getName() : string {
return self::NAME;
}
public function getStorageKey() : string {
return self::NAME;
}
public function setSomeText(string $text) {
$this->set('some-text',$text);
}
public function getSomeText() {
return $this->get('some-text');
}
}
Here is my controller...
class SessionBenchController extends AbstractController
{
public $requestStack;
public $sessionBag;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
try {
$this->sessionBag = $this->getSession()->getBag(TestSessionBag::NAME);
error_log('found existing bag');
} catch(\Exception $ex) {
error_log('constructing new bag');
$this->getSession()->registerBag(new TestSessionBag());
$this->sessionBag = $this->getSession()->getBag(TestSessionBag::NAME);
}
}
/**
* @Route("/session", name="app_session_bench")
*/
public function index(): Response
{
// $text = $this->getSession()->get('some-text');
$text = $this->sessionBag->get('some-text');
error_log('in index, text = '.$text);
return $this->render('session_bench/index.html.twig', [
'some_text' => $text
]);
}
/**
* @Route("/session/some-text", name="app_session_some_text")
*/
public function someText(Request $request): Response
{
$text = $request->request->get('text');
error_log('in someText, text = '.$text);
// $this->getSession()->set('some-text',$text);
$this->getSession()->getBag(TestSessionBag::NAME)->get('some-text');
return new JsonResponse(['success' => 1]);
}
public function getSession() : Session
{
return $this->requestStack->getSession();
}
}
The bag is never found in the constructor. It is constructed fine on the first request, but on the second request I get "Cannot register a bag when the session is already started".
In framework.yml I am using the native file handler...
session:
# handler_id: null
handler_id: 'session.handler.native_file'
save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
If I use the default handler, it seems to work. However it still does not find the bag in the constructor...the bag must be registered for every request. But the session is already started! So I am wondering why I don't get the same error as I did with native file handling.
I would assume the problem with the native file handling is the serialization but I can't find any documentation on it. I tried adding JSON serialization to the bag to no effect. What am I missing here?