The autoloaded files probably haven't been loaded yet. Add $this->load->library('ion_auth') to the top of the method.
Ion Auth check login from MY_Loader class
-
05-06-2023 - |
Question
This may be a basic Codeigniter (or php) question, but I'm trying to check if a user is logged in with Ion Auth for every page call so I can provide a 'Sign-in' or 'Sign-out' link.
I have my header, content, and footer views loading from MY_Loader class and was trying to use $this->ion_auth->logged_in()
to check if a user is logged in, but I get this php error,
PHP Error: Undefined property: MY_Loader::$ion_auth
Here is MY_Loader.php:
<?php
/**
* /application/core/MY_Loader.php
*
*/
class MY_Loader extends CI_Loader {
public function template_main($template_name, $vars = array(), $return = FALSE)
{
$vars['signin'] = $this->ion_auth->logged_in() ? 'signout' : 'signin';
$vars['signin_text'] = $this->ion_auth->logged_in() ? 'Sign-out' : 'Sign-in';
$content = $this->view('frontend/main_template/header', $vars, $return);
$content .= $this->view($template_name, $vars, $return);
$content .= $this->view('frontend/main_template/footer', $vars, $return);
if ($return)
{
return $content;
}
}
}
/* End of MY_Loader.php */
/* Location: ./application/core/MY_Loader.php */
I am autoloading the ion_auth library. How can I call the logged-in() function in MY_Loader class?
Solution
OTHER TIPS
EDIT: I misread the question, so sorry. But I'm leaving the answer up for future readers that might find it useful. Try using a hook to solve your problem.
My suggestion is to simply check if the user is logged in from your controller's constructor method and save the result to a class variable.
$this->user_logged_in = (bool)$this->ion_auth->logged_in();
This would let you make the call once for each controller, instead of once for each view (easier to maintain, and keeping basic ACL/logic out of the view). Then all you need to do is pass the variable to your view.
$data['user_logged_in'] = $this->user_logged_in;
$this->load->view('view_file_name', $data);
What I like to do when I want the entire app to require a login is to call these types of checks via CodeIgniter's hooks. In this case, maybe the post_controller_constructor
hook, this way it's called automatically (just make sure to filter out the pages you want to ignore this check, i.e.. login & register, etc).