Skip to content

ActiveRecord Class Mod

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

This page describes a modified version of the great ActiveRecord_Class library.

[b]Updated on 05 Nov 2007.[/b]

[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 [b].save()[/b] or [b].update()[/b], but not [b].create()[/b] or [b]find_*()[/b][/b].

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 [b]eval()[/b] 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: [b]join_related()[/b] which JOINs all tables this one [i]belongs_to[/i].

For instance, let us imaging we have a people and groups tables. Each person belongs to a group. People table has three columns '[i]id[/i]','[i]group_id[/i]' and '[i]name[/i]', while groups table has '[i]id[/i]' and '[i]name[/i]'. 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]

    <?php foreach($people as $person): ?>
  • <?= $person->name ?> (<?= $person->group_name ?>)
  • <?php endforeach; ?>
Clone this wiki locally