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 = $this->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:
In your model:
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:
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: