Repository navigation
ORM edit
CotORM is a basic ORM tool for the Cotonti CMF. It consists of only one
file with one abstract class. It's intended to be placed inside the Cotonti
system folder, so it can be easily included in modules using cot_incfile().
First, make sure you include the ORM system file, along with the MVC helper (to autoload models):
require_once cot_incfile('mvc', 'core');
require_once cot_incfile('orm', 'core');Your module should have a folder named 'models', in which you will store your model classes. If you prefer not to use the MVC helper, you can store your models in a folder named 'classes' instead. Cotonti's built-in autoloader will already look for files there.
As an example I will implement a module 'issuetracker', which contains a model named Project stored in modules/issuetracker/models/project.php:
class Project extends CotORM
{
protected static $table_name = 'projects';
protected static $columns = array(
'id' => array(
'type' => 'int',
'primary_key' => true,
'auto_increment' => true,
'locked' => true
),
'ownerid' => array(
'type' => 'int',
'foreign_key' => 'users:user_id',
'locked' => true
),
'name' => array(
'type' => 'varchar',
'length' => 50,
'unique' => true
),
'metadata' => array(
'type' => 'object'
),
'state' => array(
'type' => 'enum',
'options' => array('pending', 'active', 'closed')
),
'created' => array(
'type' => 'int',
'on_insert' => 'NOW()',
'locked' => true
),
'updated' => array(
'type' => 'int',
'on_insert' => 'NOW()',
'on_update' => 'NOW()',
'locked' => true
)
);
}The model class extends CotORM, which will make Project inherit all of
CotORM's methods and properties. Since CotORM contains all the fancy
methods, all we need to do here is configure the properties of Project. There
are two properties we have to configure: $table_name and $columns.
$table_name is the name of the database table to store Project objects. A
common convention is to use the lowercase, plural of the class name, so
'projects' in this case. CotORM will automatically prepend Cotonti's $db_x
to the table name.
$columns is where things get interesting. It is where you configure the
database columns for the objects. CotORM will automatically validate incoming
data based on the rules set in $columns. This includes variable type checking,
foreign key constraints and unique values. It also allows you to 'lock' and/or
'hide' a column from the outside world. Here's an overview:
- type (string, required): MySQL data type (lowercase), such as 'int', 'varchar', 'text' or one of the special values (see below).
- [to be implemented] required (bool): If true, the field is required. Defaults to false.
- [to be implemented] nullable (bool): If true, the MySQL column will accept NULL values and 'required' and 'minlength' flags will be ignored if the passed value is null.
- minlength (int): Minimum string length of the value.
- maxlength (int/string): Maximum display length of the value, or in case of float or decimal, a string representing precision and scale.
- primary_key (bool): If true, the column will be considered the primary key and be used as object identifier.
- foreign_key (string): Table and column name pair which the column is
directly related to. CotORM will enforce the foreign key dependency.
Table and column name must be seperated with a colon. Table name should not
include
$db_x. Example: 'users:user_id' - index (bool): If true, sets an MySQL INDEX on this column.
- unique (bool): If true, sets an MySQL UNIQUE constraint on this column.
- auto_increment (bool): If true, sets the MySQL AUTO_INCREMENT flag on this column.
- default_value: MySQL DEFAULT value. If foreign_key is given, this is the only value which will pass even if such a foreign record doesn't exist.
- on_insert (string): Default value for the column in INSERT queries. Accepts several special values, see the listing below.
- on_update (string): Default value in UPDATE queries. Also accepts special values.
- locked (bool): Disallows UPDATE queries on this column.
- hidden (bool): Makes the column not appear in result objects.
- alphanumeric (bool): Enforces values to be alphanumeric.
- options (array): Numeric array of allowed values. Must be used in conjunction with the 'enum' type. The first option becomes the default_value, unless another default_value is defined.
- object: Allows storage of PHP objects. Data automatically be serialized/unserialized and stored as text.
- [to be implemented] enum: Allows storage of one of a predefined set of options. Allowed values must be defined in the 'options' column property (numeric array). Data will be stored as as TINYINT (option key) but returned as the original value (string).
- NOW() => current UNIX time (integer)
- RANDOM() => random alphanumeric string or integer of maxlength length
- [to be implemented] PLUS() => Add one ($value++). Sets 0 on_insert.
- [to be implemented] MINUS() => Subtract one ($value--). Sets 0 on_insert.
$name = cot_import('name', 'P', 'TXT', 50);
$desc = cot_import('desc', 'P', 'TXT');
if ($name && $type)
{
$obj = new Project(array(
'name' => $name,
'metadata' => array(
'description' => $desc
),
'ownerid' => $usr['id']
));
if ($obj->insert())
{
// succesfully added to database
}
}The insert() and update() methods are wrappers for a more generic function
called save(). This method can take one argument, which can either be 'insert'
or 'update'. If you don't pass this argument it will try to update an existing
record and if that fails try to insert a new record. The save() method has 3
possible return values: 'added', 'updated' or null. insert() and update()
return a boolean.
It is not necessary to import each property of an object separately from form input, with CotORM it can be done at once:
$obj = Project::import();
if ($obj->insert())
{
// succesfully added to database
}The import() method attempts to import all data columns from input data depending on current request method and returns an imported object as a result.
To get existing objects from the database, CotORM provides three
'finder methods'. These basically run a SELECT query on the database and return
rows as objects of the type the finder method was executed on. The three
variants are find(), findAll() and findByPk(), which respectively will
return an array of objects matching a set of conditions, return an array of all
objects or return a single object matching a specific primary key.
Here's an example use case, listing all projects and assigning data columns to template tags:
$projects = Project::findAll($limit, $offset, $order, $way);
if ($projects)
{
foreach ($projects as $project)
{
foreach ($project->data() as $key => $value)
{
$t->assign(strtoupper($key), $value, 'PROJECT_');
}
$t->parse('MAIN.PROJECTS.ROW');
}
$t->parse('MAIN.PROJECTS');
}This is convenient for lists, but what about a details page of a specific object? Here's how to do that:
$id = cot_import('id', 'G', 'INT');
$project = Project::findByPk($id);
foreach ($project->data() as $key => $value)
{
$t->assign(strtoupper($key), $value, 'PROJECT_');
}CotORM provides a way to simplify the install and uninstall files of your
module. It has two useful methods for setup, createTable() and dropTable().
createTable() will create the table based on the configuration provided in the
model. For example, issuetracker.install.php file may look like this:
require_once cot_incfile('orm', 'core');
Project::createTable();
Milestone::createTable();
Issue::createTable();issuetracker.uninstall.php will look similar, except that it should call
dropTable() instead of createTable(). Of course you might choose not to drop
the tables upon uninstallation, but that's your choice as a developer.