Page 1 of 1

class in session?

Posted: Mon Mar 24, 2008 10:08 pm
by Sequalit
Is it okay to put a class into a session variable?

Say a database class for instance?

This way my database class only has to make one connection, and all of my modules can use it, then close at the very end?

Otherwise, right now I'm created the database class at the top, then passing it to the needed classes


Example
index.php

Code: Select all

 
$database = new Database();
$database->connect();
 
$login = new Login($database);
$page = new Page($database, "Index.html");
 
$database->close();
 
Is it okay to do it this way? So that my other pages just have to refer to the session instance of the class?

index.php

Code: Select all

 
$_SESSION['database'] = new Database();
$_SESSION['database']->connect();
 
$login = new Login();
$page = new Page("Index.html");
 
$_SESSION['database']->close();
 

Re: class in session?

Posted: Mon Mar 24, 2008 10:28 pm
by Weirdan
Sequalit wrote:Is it okay to put a class into a session variable?
Yes, any variable can be serialized into session, including objects. Except variables of 'resource' type, so for your particular situation:
Sequalit wrote: Say a database class for instance?
the answer is 'No' because database connections are resources.

Re: class in session?

Posted: Tue Mar 25, 2008 12:33 am
by Jenk
but it is possible to implement __sleep and __wake to close and restore the resource.

Re: class in session?

Posted: Tue Mar 25, 2008 2:28 pm
by Sequalit
I will be closing the database connection at the end of the page display.

I am not planning on keeping the database connection open while the user is browsing the site.

So I will have to pass a database class through method calls, I cant put it in a session? (as in example 1)

Re: class in session?

Posted: Tue Mar 25, 2008 3:09 pm
by Christopher
I am not sure why you were using the session in the first place, given what you just wrote. Your first example is the preferred way.

Re: class in session?

Posted: Wed Mar 26, 2008 1:46 am
by timvw
I agree with arborint (but that is nothing new ;)).

- Sessions are a mechanism to transfer data between requests.. Since you are talking about "modules" i'll presume that they all execute in a same (single) request and thus are not an answer to your problem...

- Right now you seem to be injecting the Database instance via the modules' constructor which is a design that usually allows for flexibility...

Re: class in session?

Posted: Wed Mar 26, 2008 10:45 am
by Sequalit
aite you guys convinced me :P

Thank you for the shared knowledge