Automatically save PHP class to database | PHP | Object mapping

Here is a class that you can use to save your models to the database every time they are changed. This allows the state of your object to persist. This will make sure that your model (class or object) is being stored and it will be mapped to the database or retrieved from the database based on its ID.
Here is how it works:
You create a model (see Dining_Room_Model) and a mapping class (see Dining_Room_DB_Mapper). You give the mapping class the data it needs to identify the object and where to store it in the database.

class Dining_Room_DB_Mapper extends DB_Property_Object {
function __construct($init_id = 0) {
$this->model = new Dining_Room_Model();
$this->id = $init_id;
$this->db_table_name = 'dinning_room';
$this->db_key = 'object';
$this->populate();
}
}
You tell the mapping class where the model is that you want to store (see above: $this->model = new Dining_Room_Model();). Then this mapping class inherits from a class (DB_Property_Object) that detects any changes in the model and automatically saves a new seriallized version of the model to the database. The model can be retrieved from the database by ID or it creates a new entry if the ID does not already exist. Be aware of too many database accesses as this code could create a bottle next to your database. I would suggest reworking the code to only save on a save command being issued so that it saves all changes instead of saving it every time one of the properties are accessed.
Check out the code below for the full and complete example:


comments powered by Disqus