I've often struggled with database calls--not from a coding standpoint, but from the standpoint of how to make them more self-maintaining. My dream would be this:
This would be perfect if PHP called the destructor once your class object leaves scope. Then all you'd have to do it place the include file at the top of a page, instantiate an instance of the class where needed, and the server would disconnect from the database at the first appropriate moment. This would be beautifully clean since a parameter sent to the constructor could affect the database user one connects with--a great way to control read/write permissions. I haven't updated to PHP 5 yet, but my understanding is that one must still make an explicit call to the destructor. Please correct me if I am wrong!
That said, how do you personally manage database connections (specifically disconnecting)? Do you use classes at all? A particularly annoying problem for me is when I initialize a connection, close it, and then realize a parent block still wanted to use the database. Oops...
- An include file which contains the database connection code
- A class within this include file that contains a class
- A constructor which connects to the database
- a destructor which closes the connection
This would be perfect if PHP called the destructor once your class object leaves scope. Then all you'd have to do it place the include file at the top of a page, instantiate an instance of the class where needed, and the server would disconnect from the database at the first appropriate moment. This would be beautifully clean since a parameter sent to the constructor could affect the database user one connects with--a great way to control read/write permissions. I haven't updated to PHP 5 yet, but my understanding is that one must still make an explicit call to the destructor. Please correct me if I am wrong!
That said, how do you personally manage database connections (specifically disconnecting)? Do you use classes at all? A particularly annoying problem for me is when I initialize a connection, close it, and then realize a parent block still wanted to use the database. Oops...
Comment