CodeIgniter Forums

Full Version: Creating multiple instance of same Model
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]rockacola[/eluser]
Hi guys, I have been working on few small CodeIgniter projects for a while now, and today I have ran into something I personally found it quite interesting and want to share with you guys. Smile

I've been coding under PHP4.4 environment since the previous CI project was all host in PHP4, except a new project I have uploaded today, which is running under PHP5. After upload, I realized the site did not work straight away and have so far found 2 main problems:

1: output_buffering, I'll start a separate discussion...

2: Code like this are pass by reference (while it is pass by value in PHP4)
Code:
$CI->load->model('Category_model');
foreach($results as $result)
{
    $category = $CI->$category_name;
    
    // Populate Category model with values
    $category->id = $result['ID'];
    
    // Populate Categories model
    $categories_model->add($category);
}
I has no problem with this in PHP4, however when in PHP5, line $category = $CI->$category_name; is passed by reference, causing all the category models identical.

After that I realized I need to utilise $this->load->model('Category_model', 'category_name'); syntax (found half-solution on thread: http://ellislab.com/forums/viewthread/49403/). Now the next problem come down to how am I able to give unique name to each instance of the category model.. and this is how I hacked it:
Code:
foreach($results as $result)
{
    $category_name = 'category-'.rand();
    $CI->load->model('Category_model', $category_name);
    $category = $CI->$category_name;
    
    // Populate Category model with values
    $category->id = $result['ID'];
    
    // Populate Categories model
    $categories_model->add($category);
}

I found this walk around hideous, but that's the best I can think of without discarding usage of Categories_model.

After today's experience, I've couple of questions pop up in my head...
1. Is there a better way to 'clone' an object in PHP5, while remain backward compatible?
2. Does it look strange to have a collection model like Categories_model?