Orm
Orm is short for Object
Relational Mapper which does 2 things: it maps your database table rows to objects and it allows you
to esteblish relations between those objects.
It follows closely the
Active Record Pattern, but was also influenced by other systems.
Creating Models
Creating a model takes little time, the convention is to use the Model_ prefix and thus place them in app/classes/model/ but you are free to use whatever name you choose.
class Model_Article extends Orm\Model {}
The above only works with the MySQL and MySQLi drivers because it needs to fetch the model properties from the database. It is however not very efficient and thus discouraged to use it this way because you'll always need that one extra query per model just to fetch the columnnames.
class Model_Article extends Orm\Model {
protected static $_properties = array('id', 'title', 'contents', 'publish');
}
Configuration
You can add static properties to the Model to configure it. As we've seen there are none required but
setting $_properties is encouraged. All these can be both public and
protected but may NOT be private.
Note that all configuration properties are prefixed with a single underscore to prevent collisions with
your column names.
protected static $_table_name
When this isn't set the Model_ prefix is removed from the classname and the classname is pluralized. Thus "Model_Article" expects table "articles". If you don't follow this convention you can change it by setting the $table_name property.
class Model_Article extends Orm\Model {
protected static $_table_name = 'myarticles';
}
protected static $_primary_key
By default this is set to array('id'), if you use another column name or multiple primary keys you need to set this property.
class Model_Article extends Orm\Model {
protected static $_primary_key = array('aid');
}
protected static $_properties
There's already a simple example above of adding all model properties, they can also be configured by using the columnname as the key and setting options like type, label & validation.
protected static $_has_one, $_belongs_to, $_has_many, $_many_many, $_many_through
Relating models to each other is explained in Relating Models
protected static $_observers
Added observers is explained in Observers