Get Rules
Just like Validation Pre-Processing rules, DataMapper supports the ability to have rules that are run immediately after getting an object.
The purpose of these rules is to help with the transition between database value formats and object value formats. Some examples of where you might want a get rule are:
- Automatically converting a date field into a Unix timestamp.
- Converting an object that has been stored in the database as a JSON or serialized string back into an object.
- Fixing Postgres boolean columns, which are returned as 't' or 'f', instead of 1 or 0, or TRUE or FALSE.
Get rules are stored in the validation array. They look and work exactly like validation rules, except you store them under the 'get_rules' key, instead of the 'rules' keys. Also, unlike validation rules, they are never skipped.
Setting Get Rules
Simply include the rules you want to run in the 'get_rules' key on the $validation field.
var $validation = array( 'startdate' => array( 'label' => 'Start Date', 'rules' => array('required', 'valid_date'), 'get_rules' => array('strtotime') ) );
Automatic Get Rules
Datamapper ORM automatically runs intval on the $id field, as well as any in-table foreign keys. This was done to prevent errors when saving back a modified value to the database, since PHP sometimes receives a string for integer values.
Included Get Rules
Datamapper ORM does not include any special, built-in rules. However, you can use any non-related rule that is supported by Validation. These methods are probably the most useful:
- intval: Forces a string value to be an integer.
- floatval: Forces a string value to be a floating number.
- strtotime: Forces conversion of a string into a Unix timestamp.
Custom Get Rules
Please see Custom Validation for how to write your own methods. Get rules follow the exact same standards, except for two differences:
- Return values are ignored.
- Get Rules should not set an error.
Columns containing NULL
For Datamapper ORM, a NULL value signifies an empty column, so by default no get_rules will be executed. If however you do want to run them, for example to provide a default value in case the column is NULL, you can add the special rule 'allow_null' to the list of get rules for the column.