Skip to content

ActiveRecord Class Mod

World Wide Web Server edited this page Jul 4, 2012 · 38 revisions

This page describes a modified version of the great ActiveRecord_Class library. [h3]Modifications made[/h3] [h4]No caching[/h4] The discover_table_columns() method and all caching logic were ditched.

Why? First of all, CI has a nice $this->db->list_fields('table_name') method which does the same in a cross-database-implementation way. Secondly, there is a $query->list_fields() method which returns an array of field names from your query object without making any additional queries.

All in all, performance-wise you save one file read and lose one "SHOW COLUMNS FROM..." query for each table you .save() or .update() (but not .create() or .find_*()). Some hacky benchmarking's shown no difference, but the library got cleaner and there is no more "OMG, I changed my DB structure, but the old one stuck in the cache, and I forgot about that!" [h4]No eval()'s[/h4] All eval() statements were removed from the code. They were only slowing things and making the source hard to read. [h4]New functionality[/h4] A new method was added: join_related() which JOINs all belongs_to and has_one tables.

For instance, let us imaging we have a people and groups tables. Each person belongs to a group. People table has three columns 'id','group_id' and 'name', while groups table has 'id' and 'name'. You need to make a list of all people in the system and their group names.

You person model will look like this: [code]class Person extends ActiveRecord { function __construct () { parent::ActiveRecord(); $this->_class_name = strtolower(get_class($this)); $this->_table = 'people'; $this->_belongs_to = array('groups'); } }[/code]

Then somewhere in you controller: [code]$this->load->model('person'); $this->join_related(); $data['people'] = $this->person->find(ALL);[/code]

And, finally, your view: [code]

Clone this wiki locally