Database Models
Interacting with the database using PHP's provided functions is normally a mess. The model classes are what we use to write and read to the database.
Model definition
Each table in the database gets a corresponding model. Each model is defined in it's own separate file. This way we can automate table creation during installation. Each model extends the base model. The base model provides all the lookup and save methods, as well as the ID field definition. We add additional field definitions and methods in the class.
To allow multiple database backend support, we use the MDB2 database abstraction module. All field types found in MDB2 can be used here. We also add two additional types; foreignkey and array. Foreignkey allows you to make a reference to another object in the database, and array will seamlessly sanitize an array when it's stored in the database.
Here's an example of a model definition:
<?php
class Coolthing extends Base {
var $name = array('type' => "text");
var $count = array('type' => "integer");
var $someBool = array('type' => "boolean", "default" => true);
function makeSomeChange() {
$this->$someBool = true;
}
}
global $Coolthing;
$Coolthing = new Coolthing();
?>
Creating a new database object using models
Creating a new database object (or row) is simple.
$newRow = new $Coolthing(array(
"name" => "foo",
"count" => 42
));
Note that the row/object is not inserted until you call the save() method (see below)
Changing values
Changing values is also very simple
$somerow->property = "foo";
Again, note that the row/object is not modified until you call the save() method (see below)
Methods
Here are the methods defined in the base model. You can define additional methods in the definition, but we provide these to make things easy:
- get(integer $id)
- Looks up a row in the database with the given ID and returns a model with it's information in it. Returns false if the object does not exist.
- filter(string $field, string $value) OR filter(array $properties)
- Looks up rows in the database with the given property/properties, and returns an array of models with these values. Returns false if no objects were found.
- save()
- Saves changes made to the model. This must be an existing model, or a new instance of a model.
Database API
The models have an internal database API that you can use in your custom methods:
- _connect()
- Connects to the database. Will not connect more then one time, so you don't need to check for a connection.
- $_link
- This is an MDB2 instance that is created after you call _connect(). All methods available in MDB2 are available in this.
- _query(string $sql, [array $valueList])
- Executes $sql, and replaces any occurring question marks (?) with a corresponding value in $valueList.
