Two years ago it was thought a single object with functions such as $database->get_user_from_id($ID)
would be a good idea. The functions return objects (not arrays), and the front-end code never worries about the database.
This was great, until we started growing the database. There’s now 30+ tables, and around 150 functions in the database object. It’s getting impractical and unmanageable and I’m going to be breaking it up.
What is a good solution to this problem? The project is large, so there’s a limit to the extent I can change things.
My current plan is to extend the current object for each table, then have the database object contain these. So, the above example would turn into (assume “user” is a table) $database->user->get_user_from_id($ID)
. Instead of one large file, we would have a file for every table.
4
First off, forget about tables. Tables are storage. Think about your classes instead. Often classes can be saved in a single table, but not always. So dont think of them as interchangable. They are very different things.
What you want to do is move the database queries into your classes. Keep the database abstraction layer – just use it to execute queries that are passed into it.
So, instead of this:
$u = $database->user->get_user_from_id($ID);
do this:
$u = new User( $ID);
The constructor of the User class would handle loading the user from the db.
class User
{
__construct( $id)
{
global $database;
$database->Query( "select name, etc... from users where id = ?", $id);
//load the object from query result
}
}
You then extend it so that it can do other tasks:
$u = new User( $ID);
$u->Email = "[email protected]";
$u->Save();
Where Save() might be
function Save()
{
global $database; //there are other ways to do this, but you get the idea
$database->query("update users set ......");
}
Now you actually have classes doing what they should be doing – the User class worries about users. The Database class worries about the database connection.
What i would recommend to you is to make a database class that knows how to run commands aganst the database and return things in a way you like make it expandable and easy to work with so you can do easy things like the following.
$table('user')->select('*')->where('user_id', 1234, '=')->exec();
that will make it easy to expand that is not the best example but look into active record like suggested, also the one in code igniter is pretty good.
Then extend that class will all the tables that you need to work with. or group them byh the type of call that should make it easy for you to be able to keep everything nice and up to date and have smaller classes.