ORM Model Class

The ORM Model Class is not only the container for a database record, it also provides methods to manipulate the object and its data.

cached_object($objpk, $class = null)

The cached_object method allows you to retrieve specific model object from the object cache, by primary key and model class name.

Static Yes
Parameters
Param Default Description
$objpk required The primary key value of the model object you want to retrieve. If the model has a compound primary key, you can pass the key values in an array, in the order the keys are defined in the model.
$class
null
The model you want to lookup. If not given, the current model name is used.
Returns Orm\Model | false
Example
// tries to retrieve OtherModel object with primary key value "12" from the cache
$from_cache = MyModel::cached_object(12, 'OtherModel');

condition($type = null)

The condition method allows you to retrieve the models defined conditions.

Static Yes
Parameters
Param Default Description
$type
null
The type of condition you want to retrieve. Currently supported are 'order_by' and 'where'. When no type is given, all conditions are returned.
Returns array()
Example
// tries to retrieve MyModel where conditions
$where = MyModel::conditions('where');

connection($writeable = false)

The connection method allows you to retrieve the models defined database connection.

Static Yes
Parameters
Param Default Description
$writeable
false
The type of connection you want to retrieve. A model can have seperate connection definitions for read and write operations. By default, the read connection is returned.
Returns string | null
Example
// retrieves the MyModel write connection
$where = MyModel::connection(true);

find($id = null, $options = null)

The find method allows you to retrieve record as a model object or an array of model objects.

Static Yes
Parameters
Param Default Description
$id
null
The primary key of the record you want to retrieve, or one of the special keywords 'all', 'first' or 'last'.
$options
null
Array of options that can be passed, including relations and query conditions.
Returns Orm/Model | array | null

See the CRUD documentation for detailed examples on how to use this method.

flush_cache($class = null)

The flush_cache method allows you to (selectively) delete model objects from the object cache.

Static Yes
Parameters
Param Default Description
$class
null
If not given, the entire cache is emptied. Optionally you can specify a model (either as a string containing a class name, or a model object, and only flush the cache for that model.
Returns void

primary_key()

The primary_key method returns an array with the column names that define the tables primary key.

Static Yes
Returns array
Example
// returns array('id') for default PK's
$pk = MyModel::primary_key();

implode_pk($data)

The implode_pk method allows you convert the value of a (compound) primary key into a string.

Static Yes
Parameters
Param Default Description
$data required Either an array with key-value pairs, or an object with properties. All column names that are part of the models primary key must be present, no validation is done.
null
is returned if the data doesn't contain all key values.
Returns string | null
Example
// with PK defined as both columns "A" and "B", this returns "[1][2]"
$pk = MyModel::implode_pk(array('A' => 1, 'B' => 2));

forge($data = array(), $new = true, $view = null, $cache = true)

The forge method allows you to forge a new model instance.

Static Yes
Parameters
Param Default Description
$data
array()
Multi-dimensional array of data to populate the new model object. This array may included data for related model objects.
$new
true
If set to
false
,
$data
must contain at least all primary key values. The object will be set to "loaded" state, as if it was retrieved from the database. This is mainly used after reading data from the database and hydrating it into model objects, or to recreate objects from data stored elsewhere, for example in an external cache.
$view
null
Used internally when models are created from on of the table views defined in the model. It changes the model object into a read-only state.
$cache
true
If set to true and
$new
set to false, and the data given contains all PK values, any existing model object is cache is returned, instead of a newly instantiated object, optionally updated with any remaining data passed.
Returns string | null
Example
// create a new MyModel model object
$mymodel = MyModel::forge();

get_filtered_properties()

The get_filtered_properties method returns the list of properties returned by a call to

to_array()
. It will take into account the list of excluded property names defined in the model.

Static Yes
Returns array
Example
// with PK defined as both columns "A" and "B", this returns "[1][2]"
$pk = MyModel::implode_pk(array('A' => 1, 'B' => 2));

Excluding properties can come in handy for properties you don't want to expose, for example if you want to return model data to the caller in a JSON response. See the static model property $_to_array_exclude.

max($key = null)

The max method returns the maximum value of the given column name.

Static Yes
Parameters
Param Default Description
$key
null
Name of a numeric table column. If not given, the primary key column is used.
Returns int | bool
Example
// get the last id issued
$last = MyModel::max('id');

This method does not support compound primary keys (as you can only query MAX() on a single column), and will return false if there is no result.

min($key = null)

The min method returns the minimum value of the given column name.

Static Yes
Parameters
Param Default Description
$key
null
Name of a numeric table column. If not given, the primary key column is used.
Returns int | bool
Example
// get the first id issued
$last = MyModel::min('id');

This method does not support compound primary keys (as you can only query MAX() on a single column), and will return false if there is no result.

observers($specific = null, $default = null)

The observers method returns a list of all observers defined in the model.

Static Yes
Parameters
Param Default Description
$specific
null
Name of a spefific observer to get the definition of. Supports dot-notation to directly get any array element in the definition. If none given, it will return all observers defined in the current model class.
$default
null
The value to return is no data was found.
Returns mixed
Example
// get the observers defined in the model
// might return array('Orm\Observer_Typing' => array())
MyModel::observers();

The array value associated with the observer in the result will contain the additional configuration the observer requires.

properties()

The properties method returns an array of all properties (i.e. column names) defined in the model class.

Static Yes
Returns array

Note: If the model does not define its properties, the ORM will attempt to generate it dynamically, by running a "list all columns" query on the defined table. As this is performance impacting, you should not use this in a production environment, but you could dump the generated array, and use that to populate the model properties array.

Not all database drivers support a "list all columns" method, and will through an exception instead.

property($key, $default = null)

The property method returns the definition of a single model class property.

Static Yes
Parameters
Param Default Description
$key required Name of a property you want to query.
$default
null
The value to return is no data was found.
Returns mixed
Example
// get the definition of the primary key
MyModel::property('id');

If no properties are defined in the model class, a call to properties() will be made in an attempt to generate them.

query()

The query method returns an ORM query object for the current model class.

Static Yes
Returns ORM\Query
Example
// get query object, and get the first record
$query = MyModel::query()->get_one();

See the CRUD documentation for detailed examples on how to use this method.

The related_class method returns the name of the ORM model class a relation maps to.

Static Yes
Parameters
Param Default Description
$relation required Name of a defined model class relation.
Returns string | null
Example
// might return "\Some\Namespace\Model_Child"
MyModel::related_class('children');

The relations method returns the ORM definition of the given relation.

Static Yes
Parameters
Param Default Description
$specific
false
Name of a defined model class relation, or
false
to return an array of all defined relations.
Returns Relation | array | false
Example
/**
 * might return:
 * object(Orm\HasMany)
 *   protected 'name' => string 'children' (length=12)
 *   protected 'model_from' => string 'Model\Parent' (length=19)
 *   protected 'model_to' => string 'Model\Child' (length=23)
 *   protected 'key_from' =>
 *     array (size=1)
 *       0 => string 'id' (length=2)
 *   protected 'key_to' =>
 *     array (size=1)
 *       0 => string 'parent_id' (length=6)
 *   protected 'conditions' =>
 *     array (size=1)
 *       'where' =>
 *         array (size=1)
 *           0 =>
 *             array (size=3)
 *               ...
 *   protected 'singular' => boolean false
 *   protected 'cascade_save' => boolean true
 *   protected 'cascade_delete' => boolean false
 */
MyModel::relations('children');

set_connection($connection)

The connection method allows you to set or override the defined database connection to be used by the model class.

Static Yes
Parameters
Param Default Description
$connection required Name of database definition, defined in the db.php config file.
Example
// switch database connection to an Oracle db
MyModel::connection('oracle');

This sets both the read and write connection, unless a seperate write connection was defined.

set_write_connection($connection)

The set_write_connection method allows you to set or override the defined database connection for writes, to be used by the model class.

Static Yes
Parameters
Param Default Description
$connection required Name of database definition, defined in the db.php config file.
Example
// switch database connection to the master db
MyModel::connection('master');

This sets the database write connection, which will override the generic connection for write queries.

table()

The table method returns the name of the table associated with the model class. If none is defined in the model, one will be generated.

Static Yes
Returns string
Example
// might return "prefix_mymodel"
$table = MyModel::table();

The generated table name will be derived from the model name, after the namespaces and any "model_" prefix is stripped, lowercase, and made plural (for english names only). So "\Some\Model_Cat" will map to a table called "cats".

delete($cascade = null, $use_transaction = false)

The delete method deletes the record associated with the current model object from the database.

Static No
Parameters
Param Default Description
$cascade
null
This argument allows you to control cascading delete behaviour.
null
is the default behavior, configured in the relations of the model.
true
or
false
explicitly enables or disables cascading deletes, or you can pass an array with relation names, if you want selective cascading deletes.
$use_transaction
false
Whether or not you want to wrap the delete in a database transaction. This allows automatic rollback, especially important when you use cascading deletes and one of them fails. Without a transaction, you'll end up with partially deleted relations.
Returns Model | false
Example
// delete the current record
$record->delete();

When the delete() operation fails logically, the method returns false. Otherwise it will return a new model instance, retaining all model data but with the primary keys reset, so a model in new state.

Note also that database exceptions that drivers might throw are not caught in this method !

disable_event($event)

The disable_event method allows you to disable a particular observer event defined in the model on a per-model instance basis.

Static No
Parameters
Param Default Description
$event required Name of the event to disable. Supported are 'after_load', 'after_create', 'after_clone', 'before_save', 'after_save', 'before_insert', 'after_insert', 'before_update', 'after_update', , 'before_delete' and 'after_delete'.
Returns void
Example
// disable the after_save observers
$record->disable_event('after_save');

enable_event($event)

The disable_event method allows you to enable a particular observer event that was disabled previously. See disable_event().

Static No
Parameters
Param Default Description
$event required Name of the event to disable. Supported are 'after_load', 'after_create', 'after_clone', 'before_save', 'after_save', 'before_insert', 'after_insert', 'before_update', 'after_update', , 'before_delete' and 'after_delete'.
Returns void
Example
// remove a defined block of all after_save observers
$record->enable_event('after_save');

from_array(array $values, $from_cache = false)

The from_array method allows you to populate a model object, and optionally related models objects, from a multi-dimensional array.

Static No
Parameters
Param Default Description
$values required Multi-dimensional array of key-value pairs, representing column names and column values.
$from_cache
false
When set to true, the model object cache will be checked before creating any related model objects from the data passed.
Returns Model, the current object, for chaining.
Example
// create a model object and populate it
$mymodel = MyModel::forge();
$mymodel->from_array($data);

//NB: this is identical to:
$mymodel = MyModel::forge($data);

Be careful with enabling $from_cache. As objects are passed around by reference in PHP, modifying a cached object with the data passed will also modify any variable containing a reference to that object. This can lead to unexpected results and possible data corruption !

get($property, array $conditions = array())

The get method allows you to get a property from the model object. Properties include columns, related objects, EAV values or custom/runtime data stored in the object.

Static No
Parameters
Param Default Description
$property required The name of the property whos value you want to retrieve.
$conditions
array()
Only used for relations that aren't fetched yet. This allows you to add additional conditions (order_by or where clauses) to the query that will fetch the related model objects. This allows you to fetch a subset, or to alter the default ordering.
Returns mixed
Example
// get all the related child records (from a defined related called 'children')
$mymodel->get('children');

get_diff()

The get_diff method returns an array with all properties that have been modified on the object since it was loaded.

Static No
Returns array
Example
// returns array('id' => 2)
$mymodel = MyModel::find(1);
$mymodel->id = 2;
print_r($mymodel->get_diff());

get_pk_assoc()

The get_pk_assoc method returns an array with a key-value pair for all primary key columns of the current model object.

Static No
Returns array
Example
// returns array('id' => 1)
$mymodel = MyModel::find(1);
print_r($mymodel->get_pk_assoc());

is_changed($property = null, $observe = false)

The is_changed method allows you to test if a model object has been altered since it was loaded.

Static No
Parameters
Param Default Description
$property
null
The name of specific property whos value you want to check for changes. If not given, or
null
, all properties will be checked.
$observe
false
Whether or not 'before_save' observers should run. This can be desirable since you could have observers defined on the model that would autonomously alter data when saving the model, without code or user interaction being involved.
Returns bool
Example
// you can use get_diff() to check what has changed
if ($mymodel->is_changed()
{
	echo "something has changed in the object !";
}

is_fetched($relation)

The is_fetched method allows you check if related objects have been loaded.

Static No
Parameters
Param Default Description
$relation required The name of the relation you want to check.
Returns bool
Example
if ( ! $mymodel->is_fetched('children'))
{
	echo "no child records have been loaded yet !";
}

Note that you can't use isset($mymodel->children), as that would access the property, which in turn would trigger a query to autoload the related records (which in turn would make is_fetched() return true) !

is_new()

The is_new method can be used to check if the object has a representation in the database, i.e. if a corresponding record exists.

Static No
Returns bool
Example
if ( ! $mymodel->is_new())
{
	echo "no record exists of this object yet";
}

Note that that if your model uses database assigned primary keys (like AUTO_INCREMENT or SERIAL), the objects primary key properties will not have a value at this point. But the absence of such values doesn't say anything about the "new" state, as the model could have primary key values that are manually assigned or generated by observers, in which case it could already have a primary key set, even though it is still classified as "new".

is_parent($all = false)

The is_new method can be used to check if the object has a representation in the database, i.e. if a corresponding record exists.

Static No
Parameters
Param Default Description
$all
false
If set to
false
, it will return
true
as soon as a relation is detected of which the current model object is a parent. Otherwise, it will check all relations, and will return an array of relations from which the current model object is a parent (which could be empty).
Returns bool | array
Example
if ($rels = $mymodel->is_parent(true))
{
	echo "don't delete it, it still has child records in " . impode(",", $rels) . " !";
}

You can use this as a manual foreign key check, either because you don't want to wait for a database driver exception in case of a foreign key violation, or because the database you work with doesn't have any foreign key constraints defined, and you want to make sure you don't want to corrupt the database by leaving child records without a parent.

reset()

The reset method deletes all changes made to the model object, and resets it to the state it was after loading.

Static No

If you call reset() on an object in "new" state, it will be completely wiped, like you had just called ClassName::forge().

save($cascade = null, $use_transaction = false)

The save method save the record associated with the current model object to the database, by using an INSERT if the object is in "new" state, or an UPDATE if not.

Static No
Parameters
Param Default Description
$cascade
null
This argument allows you to control cascading save behaviour.
null
is the default behavior, configured in the relations of the model.
true
or
false
explicitly enables or disables cascading saves, or you can pass an array with relation names, if you want selective cascading saves.
$use_transaction
false
Whether or not you want to wrap the save in a database transaction. This allows automatic rollback, especially important when you use cascading saves and one of them fails for some reason. Without a transaction, you'll end up with partially saved relations.
Returns Model | false
Example
// saves the current record
$record->save();

When the save() operation fails logically, the method returns false. Otherwise it will return true.

Note also that database exceptions that drivers might throw are not caught in this method !

to_array($custom = false, $recurse = false, $eav = false)

The to_array method allows you to convert the model object, any relational data loaded, and optionally any custom/runtime data or EAV data, to be return as a multi-dimensional array.

Static No
Parameters
Param Default Description
$custom
false
Set this to true if you want to include custom or runtime data stored in the model object.
$recurse
false
Used internally for object recursion detected. No NOT EVER set this to anything other than
false
or weird things will happen!
$eav
false
Set this to true if you want to include EAV properties stored in the model object.
Returns array
Example
// dump the contents of the current object into an array
$array = $record->to_array();

Did I mention not to set the recurse variable to anything other than false?

to_array($custom = false)

The to_array method allows you to convert the model object into a StdClass object with only the data properties.

Static No
Parameters
Param Default Description
$custom
false
Set this to true if you want to include custom or runtime data stored in the model object.
Returns StdClass
Example
// these are identical
$obj1 = $record->to_object();
$obj2 = (object) $record->to_array();