passing function to the view in CodeIgniter?
Can I pass a function to the view in CodeIgniter? The function basically checks if the session value is set. For example:
public function is_logged(){
$logged = $t开发者_如何学JAVAhis->session->userdata('user_id');
if ($logged){
return true;
} else {
redirect('index');
}
}
Now i want to place this function on some of my view. so how can i pass this function to the view? Thanks.
I would take a different approach, much like @atno said: you're using MVC pattern, so doing this kind of checks in your view is 'logically' wrong as well as going against a DRY approach.
I would do the check in controller, using the function I have in the model, and load the appropriate view according to the results:
class Mycontroller extends CI_Controller {
function index() //just an example
{
$this->load->model('mymodel');
if($this->mymodel->is_logged())
{
$this->load->view('ok_page');
}
else
{
$this->load->view('not_logged_view');
//OR redirect('another_page','refresh')
}
}
}
In your model:
function is_logged()
{
$logged = $this->session->userdata('user_id');
if ($logged)
{
return TRUE;
} else {
return FALSE;
}
}
If it's someting you need to do programmatically, for every method of a controller (like checking for being logged in), you can check inside the constructor:
function __construct()
{
parent::__construct();
// check code here
}
In this way you'll have the check before any method of the controller is called, i.e. upon controllers' initialization.
UPDATE: using a model can be overkill here, you can just check what $this->session returns:
function index() { // or mypage() or whatever
if($this->session->user_data('user_id'))
{
$this->load->view('ok_page');
}
else
{
$this->load->view('not_ok_page');
}
}
You shouldn't be doing that. Just have this code directly in your layout, or just have it in your view.
You could also create a helper : http://codeigniter.com/user_guide/general/helpers.html
精彩评论