Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load CodeIgniter models in Controller constructor

Coming from C#/.NET MVC 3/4, I'm not really used to CodeIgniter's implementation of models.

The documentation shows models being loaded within controller methods, however I'm using the model in almost every method and my model is storing data used across its methods in properties via its constructor.

Is there any reason NOT to instantiate the model in the controller constructor that I'm overlooking?

like image 990
Nick Brown Avatar asked Dec 15 '22 18:12

Nick Brown


2 Answers

You can load model as per following ways also : means if you have your model in any folder so using following code you can load model in controller.

$this->load->model('modelFolder/' . $this->controller . '_model');

For eg. : if you have your model in folder named "modelFolder" then do like this :

 class demoController extends CI_Controller {

        var $controller = "user";    

        /* Local Constructor Will Be Overriding The One In The Parent Controller Class So We Need To Manually Call It. */

        public function __construct() {
            parent::__construct();        
                $this->load->model('modelFolder/' . $this->controller . '_model');
                $this->load->model('common_model');         
              }
    }

Hope it will help you...

like image 86
Yogesh Pingle Avatar answered Dec 24 '22 19:12

Yogesh Pingle


There is no reason not to load the model for every controller activation. It could even be put in the configuration's autoload for all controllers.

The only reason not to always load it would be if many operations do not need the model. Then you could save a little bit of memory and time.

like image 39
wallyk Avatar answered Dec 24 '22 17:12

wallyk