Welcome Guest, Not a member yet? Register   Sign In
ActiveRecord for CodeIgniter: Rails-style model interactions
#49

[eluser]KJSDFHASD78FASDF78SA[/eluser]
OK, here's my two cents. I've attached my version of this nice library with all my changes:

-- I ditched discover_table_columns() method and all caching logic. 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!"
-- Removed all eval's. PHP, my love, you can do without those!
-- Added join_related() method which JOINs all tables this one belongs_to. 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 name .
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');
    }
}
Then somewhere in you controller:
Code:
$this->load->model('person');
$this->join_related();
$data['people'] = $this->person->find(ALL);
And, finally, your view:
Code:
<ul>
&lt;?php foreach($people as $person): ?&gt;
  <li>&lt;?= $person->name ?&gt; (&lt;?= $person->group_name ?&gt;)</li>
&lt;?php endforeach; ?&gt;
<ul>
-- Fixed a couple of bugs here and there.

I created a wiki page where you can download the code.


Messages In This Thread
ActiveRecord for CodeIgniter: Rails-style model interactions - by El Forum - 10-26-2007, 03:37 AM



Theme © iAndrew 2016 - Forum software by © MyBB