EllisLab text mark
Advanced Search
     
is it a good practice to load the model in the constructor function??
Posted: 06 October 2012 06:36 AM   [ Ignore ]
Avatar
Joined: 2011-08-11
47 posts

I would like to know…can I load the model in my constructor function instead of loading it for each function within that controller?

Lets say that I have 5 functions that use same model. Instad of loadin the same model in all 5 functions, should I load the controller in the construcor function like this?

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
BackOfficeUsers extends MY_Controller 
{

    
// constructor function 
    
public function __construct() 
    
{
        parent
::__construct();
        
$this->load->model('backOfficeUsersModel'); // load it here??
    
// end of constructor function 

Is this good practice or no??

 Signature 

Life is best school in the world, the only problem is that scholarship is way too expensive.

 
Posted: 06 October 2012 07:07 AM   [ Ignore ]   [ # 1 ]   [ Rating: 0 ]
Joined: 2011-10-25
62 posts

Resources that I need throughout a controller, model, or whatever type of class, I load in the constructor. I do first define these variables above the constructor as

public, protected or private $variable_name

Loading to much in the constructor can slow things down a bit

 
Posted: 06 October 2012 04:14 PM   [ Ignore ]   [ # 2 ]   [ Rating: 0 ]
Joined: 2011-10-15
5 posts

I think this is a convenience versus performance issue.  If the model is going to be used by most of your controller I would suggest loading the model in the constructor because it offers simplicity.  I also feel as though it improves the readability of the code. 

Loading to many unneeded resources in the constructor comes at a performance hit.

 
Posted: 06 October 2012 06:39 PM   [ Ignore ]   [ # 3 ]   [ Rating: 0 ]
Joined: 2009-04-15
453 posts
EzraBynx - 06 October 2012 04:14 PM

I think this is a convenience versus performance issue.  If the model is going to be used by most of your controller I would suggest loading the model in the constructor because it offers simplicity.  I also feel as though it improves the readability of the code. 

Loading to many unneeded resources in the constructor comes at a performance hit.

I don’t think that’s an issue - libraries (which included models) are loaded once, so there would be a brief uptick the first time that controller was hit is all.

I realize it’s not quite that simple, but I personally don’t concern myself with the performance part of this unless I’m building something that is going to get really pounded. Not that you should ignore best practices, but I would focus on other things to get your best performance (your db sql & interactions, for example)

Keep your code simple and easy to work with

 Signature 

Code By Jeff

Mahana Messaging Library

Problem with your query? Did you run

$this->db->last_query(); 

before you came to the forums for help?