Welcome Guest, Not a member yet? Register   Sign In
Load Model from within another Model
#1

[eluser]Jim Higgins[/eluser]
What is the best way to access or load one model from another? In other words, if I have a Apple model and want to create an Apple object from within my Fruit model class, what is the proper way to do this?

Do I simply place a require_once for the Apple class and, then, load the Apple model?
#2

[eluser]Lone[/eluser]
The first question to ask is why is one model dependant on another - this generally shouldnt happen with the MVC style. You should be using the controller as the 'middle man' to pass the data between the two models.

Absolute worst case scenario you can access in the 'apple' model in the fruit model via (if the apple model is already autoloaded):

Code:
$CI =& get_instance();
$apple = $CI->apple;
$apple->function();

But as I said make sure you just look back over your code to see if you can avoid this.
#3

[eluser]Jim Higgins[/eluser]
Hmmm... yes. I think I can do this from the controller. Didn't think of it that way. Guess my head is too far in the code and I needed to take a step back.

Thanks for helping.
#4

[eluser]Pygon[/eluser]
Typically you would make apple a storage class (an apple might be round, have a core, etc) but your manipulation functions would be part of your model (fruit->eat(the_apple), if(fruit->has_peel(the_apple) ){ fruit->peel(the_apple) }, etc.

Models are your accessors/manipulators/etc for storage types (database, object, file, etc).
#5

[eluser]wiredesignz[/eluser]
Or you could extend the Apple model off of the Fruit model rather than having two seperate models.
#6

[eluser]Jim Higgins[/eluser]
This is actually what I wanted to do... so that the Apple could inherit the props and methods of the Fruit class, but still implement it's own methods. Couple of questions on this, do I just set up the Apple constructor to extend Fruit? If so, should the Apple remain in the model folder? Is it still considered a model as a child of the Fruit?

Thanks again.
#7

[eluser]wiredesignz[/eluser]
Something like this, don't forget to load the fruit model somehow (require_once or autload etc)
Code:
class Fruit_model extends Model
{
    function Fruit_model()
    {
        parent::Model();
    }
}


class Apple_model extends Fruit_model
{
    function Apple_model()
    {
        parent::Fruit_model();
    }
}
Both belong in the models directory, yes.




Theme © iAndrew 2016 - Forum software by © MyBB