Models
Examples
In order to create and use a model, you must first define its fields and some other common data. All models are stored into includes/models/database/ by default. Let's change to that directory and create a model by duplicating the default Example.php file. You can use what ever naming convention you like for your models, but we recommend using the table name (without the prefix) as the source file name.
By now, your directory structure should look like this:
includes/
models/
database/
Example.php
YourTable.php
Into the YourTable.php file, rename the class name (Example_Record) with YourTable_Record.
You will see that we have a public method override: setUp. This must be defined by every record, since it establishes table information about the current row and defines the fields of that row. Also, make sure that:
parent::setUp()
is called before anything else in this method. We need to set the table prefix (optionally), the table name (mandatory) and the fields prefix (optional) first of all:
$this->setTablePrefix('your_table_prefix'); // can be ommitted if your table does not have a prefix
$this->setTableName('your_table_name');
$this->setFieldsPrefix('your_fields_prefix'); // if set, all fields into this table must be prefixed with this string
Now, you need to define your fields names and types. That is pretty easy, just keep in mind that only INT (and other derived types) must have a type of PDO::PARAM_INT, all others must be declared as PDO::PARAM_STR (yes, even floats and doubles!).
Suppose your table structure looks like this:
// Table "names" id INT(8) fullname VARCHAR(128) age INT(8)
The following definitions would be required:
$this->addField(array('name' => 'id', 'type' => PDO::PARAM_INT));
$this->addField(array('name' => 'fullname', 'type' => PDO::PARAM_STR));
$this->addField(array('name' => 'age', 'type' => PDO::PARAM_INT));
That's it! You can now perform basic CRUD operations using the newly created model.