Welcome to TagMyCode

Please login or create account to add a snippet.
Language: PHP
Posted by: Dylan Lopez
Added: Mar 30, 2018 3:41 AM
Views: 3182
Tags: bonfire models
  1. Bonfire Models
  2. Keeping with the MVC spirit, Bonfire uses Models to allow you interact with your database in a simple, consistent manner. By using the BF_Model as the base class for all of your models, you can very quickly setup a simple model capable of finding records, creating new and editing existing records, deleting records, checking if a key/value is unique in this table, counting the results, and more.
  4. BF_Model acts as a middleman layer between your models and CodeIgniter's standard Model class, working hand-in-hand with ActiveRecord query builder. If you don't need any special queries, your can have a working model in just a handful of lines.
  6. Sections
  8. Skeleton File
  9. Selecting Data
  10. Inserting Data
  11. Updating Data
  12. Deleting Data
  13. Utility Methods
  14. Return Types
  15. Chainable Methods
  16. Exending the Model
  17. Observers
  18. Data Validation
  19. Is it an ORM?
  20. BF_Model is not an ORM. While ORM's have their place, Bonfire does not ship with one included.
  23. A Skeleton Model
  24. To get started with a new model, you can use the following skeleton file:
  26. class X_model extends BF_Model
  27. {
  28.    protected $table_name   = '';
  29.    protected $key          = 'id';
  30.    protected $soft_deletes = FALSE;
  31.    protected $date_format  = 'int';
  32.    protected $log_user     = FALSE;
  34.    protected $set_created  = TRUE;
  35.    protected $created_field    = 'created_on';
  36.    protected $created_by_field = 'created_by';
  38.    protected $set_modified     = FALSE;
  39.    protected $modified_field   = 'modified_on';
  40.    protected $modified_by_field = 'modified_by';
  42.    protected $deleted_field    = 'deleted';
  43.    protected $deleted_by_field = 'deleted_by';
  45.    // Observers
  46.    protected $before_insert    = array();
  47.    protected $after_insert     = array();
  48.    protected $before_update    = array();
  49.    protected $after_update     = array();
  50.    protected $before_find      = array();
  51.    protected $after_find       = array();
  52.    protected $before_delete    = array();
  53.    protected $after_delete     = array();
  55.    protected $return_insert_id = true;
  56.    protected $return_type      = 'object';
  57.    protected $protected_attributes = array();
  58.    protected $field_info           = array();
  60.    protected $validation_rules         = array();
  61.    protected $insert_validation_rules  = array();
  62.    protected $skip_validation          = false;
  63.    protected $empty_validation_rules   = array();
  64. }
  65. This is the bare minimum needed to take advantage of BF_Model's built-in functions. All variables shown here are set to their default, so you don't need to show them if you are using the default values. Model_name is the name of your class and follows the same rules as CodeIgniter models.
  67. BF_Model supports quite a few ways to customize how your class works with the database.
  69. $table_name
  70. The var $table_name should be set to the name of the table in your database. If you database is set to use a prefix (Bonfire defaults to a bf_ prefix), you should leave the prefix off. So a table named bf_users should be entered as users.
  72. $key
  73. The var $key should be the name of the primary key for your table. BF_Model requires that your table has primary key. If it doesn't you should extend Model and will need to write your own methods to interface with the database. The $key is expected to be linked to an INT field.
  75. $soft_deletes
  76. Bonfire uses the concept of soft deletes that will set a flag that an item has been deleted instead of actually deleting the item. This allows you to later restore the user in case the deletion was accidental, or to keep a permanent record of any sensitive information, like transaction records.
  78. To use soft_deletes, your table must have a deleted field that is a TINYINT (1). A value of 0 means the record has not been deleted, while a value of 1 shows that the item has been deleted.
  79. The name of the deleted field may be modified by setting $deleted_field.
  81. If $soft_deletes == TRUE, Bonfire will automatically update the record to set deleted to a value of 1.
  83. If $soft_deletes == FALSE, the record will be permanently deleted from the database.
  85. $date_format
  86. Determines the type of field that is used to store created and modified dates. The possible values are:
  88. ‘int’ - A Unix integer timestamp. (This is the default)
  89. ‘datetime’ Is a MySQL Datetime field. ( YYYY-MM-DD HH:MM:SS )
  90. date’ is a MySQL Date field. ( YYYY-MM-DD )
  91. While ‘int’ seems to be one of the most common amongst PHP developers, datetime should be at least considered since it makes inspecting your data within the database much easier to interpret, though it does take a little bit more work during the script execution.
  93. $set_created
  94. Bonfire can automatically set your created on dates and times for you, in the format specified through $date_format. To use this, your table must have a created_on field of the proper type.
  96. If $set_created == TRUE, Bonfire will set the created_on field value for you at the time of an insert() call.
  97. The name of the created_on field may be modified by setting $created_field.
  99. $set_modified
  100. Bonfire can automatically set your modified on dates and times for you, in the format specified through $date_format. To use this, your table must have a modified_on field of the proper type.
  101. The name of the modified_on field may be modified by setting $modified_field.
  103. If $set_created == TRUE, Bonfire will set the created_on field value for you at the time of an insert() call.
  105. $created_field & $modified_field
  106. created_field and modified_field specify the name of the field that the time is inserted into. Defaults to created_on and modified_on.
  108. $log_user
  109. log_user provides a way to keep a small activity trail of actions related to each record. When TRUE, it will populate a field in the record with the user id. This applies to the insert, update and deleted commands, and their related methods, like update_by.
  111. The name of the fields to store the user id in can be set by changing the created_by_field, modified_by_field and deleted_by_field values. They default to created_by, modified_by and deleted_by, respectively.
  113. $deleted_field & $deleted_by_field
  114. deleted_field and deleted_by_field specify the name of the fields used to determine whether a row has been deleted (when $soft_deletes == true) and the user which deleted the row (when $log_user == true).
  116. $escape
  117. When FALSE, the select() method will not try to protect your field names with backticks. This is useful if you need a compound statement.
  119. $db_con
  120. Holds the database connection details for this model only. Can be either a string or an array as per the CodeIgniter manual. This is useful if you have a single model that needs to use a database connection different than the rest, like a logging class.
  122. $return_type
  123. Specifies whether the model returns records as an object or an array. The only valid values here are object or array.
  125. The format can be overridden on a per-call basis using the as_array and as_object methods.
  127. $user = $this->user_model->as_array()->find($id);
  128. $protected_attributes
  129. This is simply a list of keys that will always be removed from the data arrays passed to the insert, update, and similar methods. This is convenient if you like to throw your $_POST arrays directly at the model, but don't want the 'submit' inputs being saved, or for always removing the 'id' if it's passed in.
  131. protected $protected_attributes = array( 'submit', 'id' );
  132. $field_info
  133. This is an array of field definitions which may be used (in combination with prep_data()) to define the model's interaction with the database. If field_info is empty, the model will query the database to fill this array when using get_field_info(). The field_info array could also be used by a controller to help map post data to the fields in the model. See CodeIgniter's $this->db->field_data() http://ellislab.com/codeigniter/user-guide/database/fields.html
  135. The field definition should be as follows:
  137. $field_info = array(
  138.     array(
  139.         'name'          => 'id',
  140.         'type'          => 'int',
  141.         'primary_key'   => 1,
  142.     ),
  143.     array(
  144.         'name'          => 'field_1_name',
  145.         'type'          => 'varchar',
  146.         'default'       => '',
  147.         'max_length'    => 255,
  148.     ),
  149. );
  150. Provided Methods
  151. By using the skeleton file, you get a number of methods ready to use on your model. All of these methods can be overriden in your own model if you need to customize them by joining other tables, processing the results before handing off to the controller, etc.
  153. $user = $this->user_model->select(‘id, username, email’)
  154.                          ->where(‘deleted’, 1)
  155.                          ->limit(10,0)
  156.                          ->find_all();
  157. If you need to do additional processing, join tables, etc than you can do that in your model using CodeIgniter’s built-in ActiveRecord commands.
  159. class User_model extends BF_Model {
  160.     public function find_all()
  161.     {
  162.         $this->db->join(...);
  163.         return parent::find_all();
  164.     }
  165. }
  167. Selecting Data
  168. find()
  169. The find() method is used to locate a single record based on it's id.
  171. $user = $this->user_model->find($id);
  173. echo $user->username;
  174. Returns an object with the results if found, or FALSE if not found.
  176. find_by()
  177. A convenience method that combines the where() and find() methods. Expects to return a single result, so you should search on a field that will have unique values.
  179. $this->user_model->find_by('email', 'darth@theempire.com');
  180. This method can also be called with only a single associative array as the first parameter. This allows you set multiple criteria to search by.
  182. $user = $this->user_model->find_by( array('email'=>'darth@theempire.com', 'deleted'=>0) );
  184. # SQL: SELECT * FROM `bf_users` WHERE email='darth@theempire.com' AND deleted='0'
  185. This defaults to combining all criteria as "AND" but can be modified by passing the the type into the third parameter:
  187. $user = $this->user_model->find_by( array('email'=>'darth@theempire.com', 'deleted'=>0), null, 'OR' );
  189. # SQL: SELECT * FROM `bf_users` WHERE email='darth@theempire.com' OR deleted='0'
  190. find_all()
  191. Locates all records in the table.
  193. $this->user_model->find_all();
  194. If you need to modify the search criteria you can use any of the chainable methods.
  196. $users = $this->user_model->where('deleted', 1)
  197.                          ->limit(25)
  198.                          ->find_all();
  200. foreach ($users as $user)
  201. {
  202.    echo $user->username;
  203. }
  204. Returns an array of objects where each object holds the results of a single record.
  206. find_all_by()
  207. Locates all records matching certain criteria. This is a convenience method for using a where() and a find_all() in one command.
  209. $this->user_model->find_all_by('deleted', 1);
  210. Any of the standard options available to a CodeIgniter where() method may be used here.
  212. $this->user_model->find_all_by('deleted', 1);
  213. $this->user_model->find_all_by('deleted !=', 0);
  214. $this->user_model->find_all_by( array('email'=>'darth@theempire.com', 'deleted'=>0) );
  215. Returns an array of objects where each object holds the results of a single record.
  218. Inserting Data
  219. insert()
  220. Creates a new record. Will set the created_on field if the model is setup to allow that. The first parameter should be an associative array of field/values to insert.
  222. $user = array(
  223.    'email'     => 'dart@theempire.com',
  224.    'username'  => 'darth.vader'
  225. );
  226. $this->user_model->insert($user);
  228. # SQL: INSERT INTO `bf_users` (email, username, created_on) VALUES ('darth@theempire.com', 'darth.vader', 1321645674);
  229. Returns an INT ID of the new record on success, or FALSE on failure.
  231. insert_batch()
  232. Allows for inserting more than one record at a time. Works just like CodeIgniter’s stock method, but handles setting the table name for you.
  234. $data = array(
  235.   array(
  236.      'title' => 'My title' ,
  237.      'name' => 'My Name' ,
  238.      'date' => 'My date'
  239.   ),
  240.   array(
  241.      'title' => 'Another title' ,
  242.      'name' => 'Another Name' ,
  243.      'date' => 'Another date'
  244.   )
  245. );
  247. $this->db->insert_batch('mytable', $data);
  249. Updating Data
  250. update()
  251. Updates an existing record in the database by ID. Will set the correct time for the modified_on field, if the model requires it.
  253. $user = array(
  254.    'email'     => 'dart@theempire.com',
  255.    'username'  => 'darth.vader'
  256. );
  257. $this->user_model->update($user_id, $user);
  259. # SQL: UPDATE `bf_users` SET email='darth@theempire.com', username='darth.vader', modified_on=1321645674 WHERE id=1;
  260. Returns a boolean TRUE/FALSE on success/failure.
  262. update_where()
  263. Updates a single record in the database by a key/value pair. Will set the correct time for the modified_on field, if the model requires it.
  265. $user = array(
  266.    'email'     => 'dart@theempire.com',
  267.    'username'  => 'darth.vader'
  268. );
  269. $this->user_model->update('is_father', 1, $user);
  271. # SQL: UPDATE `bf_users` SET email='darth@theempire.com', username='darth.vader', modified_on=1321645674 WHERE is_father=1;
  272. update_batch()
  273. Updates multiple records with a single method call.
  275.  $data = array(
  276.     array(
  277.        'title' => 'My title' ,
  278.        'name' => 'My Name 2' ,
  279.        'date' => 'My date 2'
  280.     ),
  281.     array(
  282.        'title' => 'Another title' ,
  283.        'name' => 'Another Name 2' ,
  284.        'date' => 'Another date 2'
  285.     )
  286.  );
  288.  $this->model->update_batch($data, 'title');
  289. The first parameter is an array of values. The second parameter is the where key.
  292. Deleting Data
  293. delete()
  294. Deletes a single record from the database. If $soft_deletes are on, then will just set the deleted field to 1. Otherwise, will permanently delete the record from the database.
  296. $this->user_model->delete($user_id);
  298. # SQL w/ soft deletes: UPDATE bf_users SET deleted=1 WHERE id=$user_id;
  299. # SQL w/out soft deletes: DELETE FROM bf_users WHERE id=$user_id;
  300. Returns a boolean TRUE/FALSE on success/failure.
  302. delete_where()
  303. Deletes one or more records that match certain requirements. If $soft_deletes == true, will set the deleted field to 1, otherwise will delete the record permenantly.
  305. The first parameter accepts an array of key/value pairs to form the ‘where’ portion of the query.
  307. $wheres = array(
  308.    ‘active’    => 0,
  309.    ‘last_login’ => ‘< ‘. time()
  310. );
  311. $this->model->delete_where($wheres);
  313. Utility Methods
  314. is_unique()
  315. Checks to see if a given field/value combination would be unique in the table.
  317. $this->user_model->is_unique('email', 'darth@theempire.com');
  318. count_all()
  319. Counts all records in the table.
  321. $this->user_model->count_all();
  322. Returns an INT containing the number of results, or FALSE.
  324. count_by()
  325. Counts the number of elements that match the field/value pair.
  327. $this->user_model->count_by('delete', 1);
  328. Returns an INT containing the number of results, or FALSE.
  330. get_field()
  331. A convenience method to return only a single field of the specified row. The first parameter is the ID of the row to search in. The second parameter is the column to return the value of.
  333. $this->user_model->get_field($user_id, 'email');
  334. Returns the value of the row's field, or FALSE.
  336. get_created_field(), get_modified_field(), get_deleted_field(), get_created_by_field(), get_modified_by_field(), & get_deleted_by_field()
  337. Returns the names of the respective fields, or an empty string if the fields are not used by the model (based on the values of set_created, set_modified, soft_deletes, and log_user).
  339. get_field_info()
  340. Returns the $field_info array, attempting to populate it from the database if empty.
  342. prep_data()
  343. Intended to be called by a controller and/or extended in the model, prep_data processes an array of field/value pairs (can be the result of $this->input->post()) and attempts to setup a $data array suitable for use in the model's insert/update methods. The output array will not include the model's key, created_on, created_by, modified_on, modified_by, deleted, or deleted_by fields, or fields indicated as the primary key in the model's field_info array.
  345. For example, the user_model extends prep_data to map field names from the view that don't match the tables in the database and ensure fields that should not be set are not set:
  347. public function prep_data($post_data)
  348. {
  349.     $data = parent::prep_data($post_data);
  351.     if ( ! empty($post_data['timezones'])) {
  352.         $data['timezone'] = $post_data['timezones'];
  353.     }
  354.     if ( ! empty($post_data['password'])) {
  355.         $data['password'] = $post_data['password'];
  356.     }
  357.     if ($data['display_name'] === '') {
  358.         unset($data['display_name']);
  359.     }
  360.     if (isset($post_data['restore']) && $post_data['restore']) {
  361.         $data['deleted'] = 0;
  362.     }
  363.     if (isset($post_data['unban']) && $post_data['unban']) {
  364.         $data['banned'] = 0;
  365.     }
  366.     if (isset($post_data['activate']) && $post_data['activate']) {
  367.         $data['active'] = 1;
  368.     } elseif (isset($post_data['deactivate']) && $post_data['deactivate']) {
  369.         $data['active'] = 0;
  370.     }
  372.     return $data;
  373. }
  374. The User Settings controller then uses the model's prep_data method to process the post data before inserting/updating the user:
  376. private function save_user($type='insert', $id=0, $meta_fields=array(), $cur_role_name = '')
  377. {
  378.    /* ... Omitting validation setup and gathering of user_meta data ... */
  380.    // Compile our core user elements to save.
  381.    $data = $this->user_model->prep_data($this->input->post());
  383.    if ($type == 'insert') {
  384.        $activation_method = $this->settings_lib->item('auth.user_activation_method');
  386.        // No activation method
  387.        if ($activation_method == 0) {
  388.            // Activate the user automatically
  389.            $data['active'] = 1;
  390.        }
  392.        $return = $this->user_model->insert($data);
  393.        $id = $return;
  394.    } else {    // Update
  395.        $return = $this->user_model->update($id, $data);
  396.    }
  398.    /* ... Omitting saving user_meta data and event trigger ... */
  400.    return $return;
  402. }//end save_user()
  404. Return Types
  405. You can temporarily override the type of records returned by the model by using the folliwing commands. This allows you to use objects as a default since they consume less memory, but ask for the results as an array for a single method that you need the extra flexibilty arrays provide.
  407. as_array()
  408. A chainable method that specifies the model should return the results as an array (for single results) or an array of arrays (for multiple rows). This overrides the models $result_type class variable.
  410. as_object()
  411. A chainable method that specifies the model should return the results as an object (for single results) or an array of objects (for multiple rows). This overrides the models $result_type class variable.
  413. as_json()
  414. A chainable method that specifies the model should return the results as a JSON object suitable for returning in AJAX methods. This overrides the models $result_type class variable.
  417. Chainable Methods
  418. Thanks to CodeIgniter's ActiveRecord library, it is very simply to modify the BF_Model's methods. This can be done through either chainable methods or by extending methods.
  420. Chainable methods are a feature of PHP 5 and higher that allow you to return the results of one function into another, and to keep this 'chain' of events continuing through several functions. Bonfire duplicates several of the stock ActiveRecord methods in BF_Model to make it simple and elegant to customize your queries.
  422. Bonfire's model supports chaining for most of the ActiveRecord methods available, including:
  424. select
  425. select_max
  426. select_min
  427. select_avg
  428. select_sum
  429. distinct
  430. from
  431. where
  432. or_where
  433. where_in
  434. or_where_in
  435. where_not_in
  436. or_where_not_in
  437. like
  438. not_like
  439. or_like
  440. or_not_like
  441. group_by
  442. having
  443. or_having
  444. limit
  445. offset
  446. set
  447. All of these methods accept the same parameters as their CodeIgniter counterparts. These are included for the sole reason of making your syntax more expressive. You can now do things like:
  449. $this->user_model->where('city', 'Detroit')
  450.                  ->or_where('city', 'Cleveland')
  451.                  ->join('tour_dates', 'x on y')
  452.                  ->find_all();
  453. where()
  454. Modifies the query to a specific where condition. Can be used with any of the read-type queries (find, find_all, etc).
  456. The first parameter is the field to match against. The second parameter is the value of the field to find.
  458. Accepts any of the standard CodeIgniter ActiveRecord where statements.
  460. $this->user_model->where('email', 'darth@theempire.com');
  461. $this->user_model->where('email !=', 'darth@theempire.com');
  462. $this->user_model->where( array('email' => 'darth@theempire.com') );
  464. $this->user_model->where('email', 'darth@theempire.com')
  465.                  ->find_all();
  466. You can also pass an array of field/value pairs as the first parameter. In this case, the second parameter is ignored.
  468. $wheres = array(
  469.     ‘active’        => 1,
  470.     ‘deleted’   => 0
  471. );
  472. $results = $this->model->where($wheres)->find_all();
  474. Extending Methods
  475. While it is possible to modify the query via the chainable methods any time you need results in your controller, it is highly recommended to extend the model's methods to bring you the results you need. This keeps all of your changes to queries in a single place.
  477. Sometimes, you might want to do some additional processing to the database results before passing it on to the controller. This is another perfect example of when to extend the model's method.
  479. To extend an existing method, you simply create a new method in your model that accepts the same parameters as the original BF_Model method.
  481. // Extend the existing functionality.
  482. public function find($id=null)
  483. {
  484.     $result = parent::find($id);
  486.     if ($result)
  487.     {
  488.         $result->display_name = $this->format_name($result);
  489.     }
  491.     return $result;
  492. }
  493. Modify Query in Controller
  494. You can modify a query in your model for a single use by using CodeIgniter's ActiveRecord commands in your controllers. Since BF_Model uses the ActiveRecord commands, the changes in your controller will affect the results of the next query in your model.
  496. // In your controller.
  497. $this->db->join('other_table', 'link_field = users.id', 'left');
  498. $user = $this->user_model->find($user_id);
  500. Observers
  501. Observers provide a simple and convenient method for your models to change portions of the data at certain execution points within a model’s interaction. This can be very handy for adding in the created_on time before inserting a record, or deleting related records in other tables whenever a user is deleted.
  503. The following events can be observed by your class:
  505. before_insert
  506. after_insert
  507. before_update
  508. after_update
  509. before_find
  510. after_find
  511. before_delete
  512. after_delete
  513. empty_validation_rules
  514. These are each arrays that should have the name of the methods to call, in order of priority as the array’s elements.
  516. protected $before_insert = array(‘set_created_on’, ‘another_callback’);
  517. To observe an event and have your methods called you simply add the method name to the definition array and create a new function.
  519. protected function set_created_on($row)
  520. {
  521.    if (!array_key_exists($this->created_field, $row))
  522.    {
  523.        $row[$this->created_field] = $this->set_date();
  524.    }
  526.    return $row;
  527. }
  528. Each observing method must accept a single parameter. Depending on the event triggered, this might be a single INT, or an array of values, etc. Check the function to verify what the payload being passed along is for the event you’re observing.
  530. The following table lists what data should be expected during each observer. Note that the *_batch or *_many may exhibit slightly different behaviour. You should familiarize yourself with code for each if you need special triggers for these situations.
  532. Trigger Type    Description
  533. before_insert   array   The values to be inserted in the new record
  534. after_insert    mixed   The primary_key of the row just inserted.
  535. before_update   array   The values to be updated. Does NOT include the primary key.
  536. after_update    array   The data that was inserted (including any modifications made in before_udpate).
  537. before_find     mixed   The primary_key of the row to find.
  538. after_find      array/object    The found object/array (depends on the specified return type for that model)
  539. before_delete   mixed   The primary_key of the row to be deleted.
  540. after_delete    mixed   The primary_key of the row that was just deleted.
  541. empty_validation_rules  array   An array of temporary validation rules.
  543. Validating Data
  544. The model should contain all of the validation rules for your data so that it is always kept in a single place with the model that represents it. Bonfire's models provide a simple way to automatically have your data validated during inserts and updates.
  546. Basic Validation
  547. The $validation_rules variable can take an array of data that follows the same format as CodeIgniter's Form Validation Library.
  549. protected $validation_rules = array(
  550.    array(
  551.        'field' => 'username',
  552.        'label' => 'Username',
  553.        'rules' => 'trim|strip_tags|min_length[4]|xss_clean'
  554.    ),
  555.    array(
  556.        'field' => 'password',
  557.        'label' => 'lang:bf_password',
  558.        'rules' => 'trim|min_length[8]'
  559.    )
  560. );
  561. Note: the value of the label can be retrieved from a language file by prefixing the name of the entry in the language file with lang:, as in the example for the password field, above.
  563. During an insert or update, the data passed in is automatically validated using the form_validaiton library. If the validation doesn't pass successfully, the insert/update method will return a value of FALSE and the form_validation_ library will function as expected, providing errors through validation_errors and form_error.
  565. Insert Rules Customization
  566. Often, you will have certain rules that are slightly different during object creation than you will during an update. Frequently, this is as simple as having a field required during inserts, but not during updates. You can handle this by adding any additional rules for inserts in the $insert_validation_rules class variable.
  568. protected $insert_validation_rules = array(
  569.    'password'   => 'required|matches[pass_confirm]'
  570. );
  571. Unlike, the $validation_rules array, the $insert_validation_rules array consists of the field name as the key, and the additional rules as the value. Theses rules are added at the end of the normal rules string before being passed to the form_validation library.
  573. Skipping Validation
  574. If you need to turn off validation for any reason (like performance durin a large CSV import) you can use the skip_validation() method, passing either TRUE or FALSE to the skip or not skip the validation process. This stays in effect as long as the model is loaded but will reset the next time the model is loaded in memory. Typically the next page request.
  576. $this->user_model->skip_validation(true);
  578. $this->user_model->skip_validation(true)->insert($data);
  579. Traditional validation using the Model's validation rules
  580. If you wish to perform validation in the Controller (or another Model), you can retrieve the validation rules from the Model using the get_validation_rules() method, passing either 'update' or 'insert' to determine whether the $insert_validation_rules are added (you will probably want to disable the model's validation when calling the insert()/update() methods using the skip_validation() method or the model's skip_validation property). The rules may then be passed to CI's Form Validation library to perform validation:
  582. $this->form_validation->set_rules($this->example_model->get_validation_rules('update'));
  584. if ($this->form_validation->run() === false) {
  585.     return false;
  586. }
  587. Generating validation rules
  588. If you want to generate the validation rules in code (rather than supplying a hard-coded array), you can supply the name of a function to the $empty_validation_rules observer to generate the validation rules. The function will receive an array of the current validation rules (usually empty or a non-array value, but if multiple functions are used with the observer, it may be a valid array), and is expected to return an array of validation rules.
  590. For instance, you could create a function that uses $this->db->field_data($this->table_name) to retrieve the field information directly from the database, then iterate through the results to create validation rules for each field based on the information returned by the database.
  592. Because it is faster to use the array, the observer will not be called if the array has been set (and the array generated by the observer when it is called will be assigned to the array to prevent the current instance of the model from attempting to generate the rules again).