Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you access a model from inside another model in CodeIgniter?

Tags:

I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?

like image 796
Eldila Avatar asked Sep 05 '08 17:09

Eldila


People also ask

Can we call a model from another model?

Yes, you can call a method from another model in a model in Code Igniter. You need the model you are calling a method on to be loaded. If you autoload all your models, it will always work.

Can we call model from view in CodeIgniter?

First Model interacts withe the database. Then load the model and access relevant function in your controller. Finally load the data to view from the controller. That's it...you can show the data simply in a foreach loop.


2 Answers

It seems you can load models inside models, although you probably should solve this another way. See CodeIgniter forums for a discussion.

class SomeModel extends Model
{
  function doSomething($foo)
  {
    $CI =& get_instance();
    $CI->load->model('SomeOtherModel','NiceName',true);

    // use $CI instead of $this to query the other models
    $CI->NiceName->doSomethingElse();
  }
}

Also, I don't understand what Till is saying about that you shouldn't create objects inside objects. Of course you should! Sending objects as arguments looks much less clear to me.

like image 101
Christian Davén Avatar answered Sep 19 '22 10:09

Christian Davén


In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model.

<?php
// in your controller
$model1 = new Model1();
$model2 = new Model2();
$model2->setWhatever($model1);
?>
like image 40
Till Avatar answered Sep 20 '22 10:09

Till