Singleton DB Connection with Sessions stored in DB - problem

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
GM
Forum Contributor
Posts: 365
Joined: Wed Apr 26, 2006 4:19 am
Location: Italy

Singleton DB Connection with Sessions stored in DB - problem

Post by GM »

Hi all,

I'm using a singleton as a DB connection class, it's a plain vanilla singleton - nothing fancy at all. I'm also storing my sessions in a database, via a session class (which obviously needs to access the database). So I've changed the session handler to use my session class.

I've found however, that my Singleton works fine in the session open and session read phases, but gives me the error "could not fetch mysqli" in the write and close phases.

Can it be that the db connection class is being unloaded from memory before the session finishes?

I've found that if I don't use a singleton (that is, I create a concrete instance of the db connection and use that) then I don't get this problem, because the object seems to persist after the session. But with the singleton I get that error "Unable to fetch mysqli", in the write and close phases of the session.

I notice also that if I put a session_write_close() command immediately before the closing php tag that this problem goes away (presumably because the db connection class is still in memory at this point).

Has anyone experienced anything similar? Are there any resources that explain what PHP does (and in what order) when it reaches the closing php tag on the page?
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post by patrikG »

GM wrote:Are there any resources that explain what PHP does (and in what order) when it reaches the closing php tag on the page?
I think the question is more: "How does a session end?"
session_set_save_handler() wrote:Write and Close handlers are called after destructing objects since PHP 5.0.5. Thus destructors can use sessions but session handler can't use objects. In prior versions, they were called in the opposite order. It is possible to call session_write_close() from the destructor to solve this chicken and egg problem.
In the session-handler, I've always instantiated the db-wrapper locally or used a direct connection if I needed to store things in the DB.
GM
Forum Contributor
Posts: 365
Joined: Wed Apr 26, 2006 4:19 am
Location: Italy

Post by GM »

Thanks patrickG - that's exactly what I was looking for... I suppose I'll make the db connection within the session class instead of using the singleton.
Post Reply