How to handle database access in code
How to you handle your database access in your code?
The way I have been doing it is just creating functions like query, fetch, etc. Then in my code, I can call those functions anywhere without any problems. But now I want to try wrapping everything in a class.
But how can I access the database object from another class or function without actually passing the DB object to it every time? Just about every class I make needs access to the database.
pr0gr4mm3r posted this at 14:16 — 19th September 2008.
He has: 1,502 posts
Joined: Sep 2006
The easiest way would probably just make it a global object.
Most of the classes and functions that I write don't have access to the database. The main reason is why I break up code in classes and objects is so I can use them on other sites. If you have them use database objects specific to the site, then it will be more difficult to use it elsewhere. So, get the data from the DB first and send that to the class/function instead of having the class/function fetch the data.
teammatt3 posted this at 23:04 — 20th September 2008.
He has: 2,102 posts
Joined: Sep 2003
So the main reason for a DB abstraction layer is to enable code to be reused (some say it allows you to move to another DB platform easily, but I don't by into that argument).
I'm going to stick with functions for now because I don't like typing $GLOBALS['db']-> but maybe I'll get the hang of it someday .
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.