swordfish
swordfish

Reputation: 191

php codeigniter single function for all other function

here is some details for my question.

controller:  
function get_info()  
{  
$user_id = $this->session->userdata['logged_in']['userid']
$this->load->model('message_model');  
$msg_data['msg']=$this->message_model->get_user_msg($user_id); 
$this->load->view('header',$msg_data);  
$this->load->view('content');  
$this->load->view('footer');     
}  

function others_goes_here()  
{  
$user_id = $this->session->userdata['logged_in']['userid']
$this->load->model('message_model');  
$msg_data['msg']=$this->message_model->get_user_msg($user_id); 
LOAD OTHER VIEWS.....    
}
model:
function get_user_msg($user_id)
{
QUERY GOES HERE......
}  

Now what i want to achieve is how can i make the get_user_msg to be called only once without calling it to all my other functions. Hope you guys can help me with this,
thank in advance.

Upvotes: 0

Views: 108

Answers (2)

Syed Sajid
Syed Sajid

Reputation: 1410

Well use construct function for that

public $user_msg;
function __construct()
{
    parent::__construct();
            $this->load->model('message_model');
            $user_id = $this->session->userdata['logged_in']['userid']
            $this->user_msg=$this->message_model->get_user_msg($user_id);

}
function AllOtherFunctions(){
     $this->user_msg; //you will have it ready every where
}

Upvotes: 1

Yan Berk
Yan Berk

Reputation: 14428

You create a class variable and run get_user_msg from the constructor:

protected $msg_data;

function __construct() {
     parent::__construct();
     $this->load->model('message_model'); 
     $user_id = $this->session->userdata['logged_in']['userid']
     $this->msg_data = $this->message_model->get_user_msg($user_id);
}

function function get_info() {
     $this->load->view('my_view', $this->msg_data);
}

Upvotes: 2

Related Questions