Reputation: 3253
is it possible to call a common function through out a website using codeigniter?
Im have built a CMS using codeigniter 3 and it has messaging option. On the header of the site i am showing the count of unread messages
currently i have included the below code to all the models
function get_unread_count($id)
{
$this->db->where('to',$id);
$this->db->where('read',0);
$x = $this->db->get('messages');
return $x->num_rows();
}
and i call it in all the controllers.
Is there any simplified way for this?
Upvotes: 1
Views: 2637
Reputation: 682
make the one model common and add it on route file
$autoload['model'] = array('mdl_common');
like this above set method of autoload . and put your function in this model like this below line of code
class Mdl_common extends CI_Model
{
function get_unread_count($id)
{
$this->db->where('to',$id);
$this->db->where('read',0);
$x = $this->db->get('messages');
return $x->num_rows();
}
}
and call this function in your header file like this below line of code
$this->mdl_common->get_unread_count($id); // i don't know what id you were passing
but try like this flow hope will helps you
Upvotes: 0
Reputation: 2468
Helper functions are available all over project you can call helper function in any controller directly.
Create a file in helper directory as application/helper/common_helper.php and place function in file.
Now configure helper-name in routes.php for auto-load as : $autoload['helper'] = array('common_helper');
Now you will be able to call helper function without object in all the controllers Ex. get_unread_count($id);
Please note: $this->db
object will not be available in helper so you need to create codeigniter instance and use:
$ci =& get_instance();
$ci->db->query();
Upvotes: 1
Reputation: 3148
Building on what Luciano is saying - at every page you have to confirm who the user is through a session check or similar. So at the same time you can update the message count in the session for the new page. That way you don't have to call the message count function from every controller, its just part of the user validation process.
Also something to keep in mind is that instead of just validating the user - you can return a user record - either an object or array - to use in different ways like for their name etc. In other words you don't always have to write things and retrieve them from a session. Finally consider having a separate template for logged in users. That can help keep things separated.
Upvotes: 0
Reputation: 11
Use Session variables (CI_SESSION) to store the data once per session, so you can refer to:
$this->session->userdata(your_msg_number)
directly into the view, and delegate getting message number once a session. Also setting data dinamically will update the value on page refresh providing:
$this->session->set_userdata('your_msg_number_variable_name', msg_number)
If you prefer AJAX you can set a javascript to point a controller that provide the message numbers via JSON....
Upvotes: 1