Basically, you have three approaches to this problem (one of which I will fix immediately):
- One table for each class (this is the one I will delete);
- Type of record with additional columns; and
- The type of record with the child table, depending on the type you are joining.
For simplicity, I usually recommend (2). So, as soon as you have a table:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, type VARCHAR(10), name VARCHAR(100) );
where the type can be "AGENT" or "LEAD" (for example). Alternatively, you can use a single character type code. Then you can start filling in the blanks using the object model:
- You have the parent class of the user;
- You have two child classes: Lead and Agent;
- These children have a fixed type.
and he should easily fall into place.
As for loading in one of the operators, I would use some kind of factory. Assuming these barebones classes:
class User { private $name; private $type; protected __construct($query) { $this->type = $query['type']; $this->name = $query['name']; } ... } class Agent { private $agency; public __construct($query) { parent::constructor($query); $this->agency = $query['agency']; } ... } class Lead { public __consruct($query) { parent::constructor($query); } ... }
a factory might look like this:
public function loadUserById($id) { $id = mysql_real_escape_string($id); // just in case $sql = "SELECT * FROM user WHERE id = $id"; $query = mysql_query($sql); if (!query) { die("Error executing $sql - " . mysql_error()); } if ($query['type'] == 'AGENT') { return new Agent($query); } else if ($query['type'] == 'LEAD') { return new Lead($query); } else { die("Unknown user type '$query[type]'"); } }
Alternatively, you can use the factory method as a static method, for example, for the User class and / or use the lookup table for types for classes.
It is possible that contaminating classes with a query result resource like this is a dubious design in the strict sense of OO, but it just works.
cletus
source share