[eluser]paulodeleo[/eluser]
Hi,
I started using codeignitor a few days ago, and noticed something that I don't know if is caused by some mistake of mine (just wrong design being used), or a limit/bug in php or codeignitor .
The problem is when I need to use models inside models, and return an array of this model objects to the controller. Looks like the "submodels" loose their references. To the controller, all "submodels" are the same, the last instance of the "submodel".
Sorry for my english. Maybe the best way to explain is with some sample code of the problem.
fruit.php (model, the one I call "submodel"):
Code:
<?php
class Fruit extends Model {
public $id;
function __construct()
{
parent::Model();
}
}
?>
tree.php (model, buggy)
Code:
<?php
class Tree extends Model {
public $id;
function __construct()
{
parent::Model();
$this->load->model("fruit");
}
function load($id)
{
$this->id = $id;
$this->fruit->id = $id;
}
function listAll()
{
$objArray = array();
for($i=0; $i<=3; $i++)
{
$obj = new Tree();
$obj->load($i);
$objArray[]=$obj;
}
return $objArray;
}
}
?>
test.php (controller):
Code:
<?php
class Test extends Controller {
function index()
{
$this->load->model("tree");
foreach ($this->tree->listAll() as $tree)
{
echo "tree: " . $tree->id . ", fruit: " . $tree->fruit->id . "<br>";
}
}
}
?>
Browser output (buggy version):
Code:
tree 0, fruit 3
tree 1, fruit 3
tree 2, fruit 3
tree 3, fruit 3
The problem is all fruits to show id 3, when I expect the same id as it's tree.
To fix it, I must do some changes:
tree.php (model, fixed with workaround)
Code:
<?php
//1 - Must require the fruit class...
require_once("fruit.php");
class Tree extends Model {
public $id;
//2 - Create a public property for the fruit object...
public $fruit;
function __construct()
{
parent::Model();
//3 - Remove CI's loading of the model and use the native php one
//$this->load->model("fruit");
$this->fruit = new Fruit();
}
function load($id)
{
$this->id = $id;
$this->fruit->id = $id;
}
function listAll()
{
$objArray = array();
for($i=0; $i<=3; $i++)
{
$obj = new Tree();
$obj->load($i);
$objArray[]=$obj;
}
return $objArray;
}
}
?>
Expected browser output (fixed by workaround):
Code:
tree 0, fruit 0
tree 1, fruit 1
tree 2, fruit 2
tree 3, fruit 3
Then the output is right. But you can imagine how ugly (and wrong?) the code can be in a real world situation. Lots of requires in every model in the "chain", etc.
So, if the code is wrong in some way, how codeignitor must be used to produce the expected output?
Or, if it's really some kind of bug, any other suggestions to solve it?
Using PHP 5.2.6 on a Linux box here.
Thank's for any help!