Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Roni's avatar
Level 33

Objects in Session with methods

I found quite by accident that while writing a test to store and retrieve an object id, and I had actually (accidentally) stored a complete object on the session.

EDIT: After re-reading this once, some clarification:

  1. $this->topicis set up in the setup() funciton
  2. $this->submitNoExceptions()just runs the request against the endpoint I'm testing against and returns a TestResponse Object. It has not bearing on the actual question of the object in the session.

Here is the test in two parts

/** @test */
public function session_has_last_entered_object() {
    $this->submitNoExceptions()
        ->assertSessionHas('last_entered_type', Question::class);
    $this->assertTrue(session('last_entered_id')->is(Question::last()));
    

    //the second part

    $question = session('last_entered_id');
    $this->assertTrue($question->topic->is($this->topic));

    //will fail - part 3
    //$this->assertEquals($question->topic,$this->topic);

}

Of course it started wrong as initially I had $this->assertTrue(session('last_entered_id')->is(Question::last()->id)); however, after the error instead of immediately correcting it, it occurred to me (for this use case at least) there is no problem with any race condition and I could save myself one database call on the next request by simply accessing the session variable.

After looking at some searches the main drawback in this situation, was that it was going through some magic serialization and it was just data. You couldn't run methods off of the object. However it clearly is working as the object based on the "second part".

There is another follow up that I noticed. I tried modifying this to use assertEquals instead of the ìs()unction and it did fail. The difference was the "wasRecentlyCreated" property.

Some questions:

  1. Is it a terrible practice?
  2. Are you actually saving queries? Based on that part 3 it looks like it may not be.
  3. Can anyone weigh in on pro's and cons as to when this might be appropriate or what is hazardous.

Thanks

0 likes
0 replies

Please or to participate in this conversation.