I am attempting to create a constructor for my controller that references a function that I have contained in a helper which is autoloaded.
The function checks whether or not the user is logged in, if so it redirects them to the login page.
It appears that I have not setup the construct correctly as I am receiving the following error:
Fatal error: Call to undefined method Profile::is_logged_in()
This is the controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
//function inside autoloaded helper, check if user is logged in, if not redirects to login page
$this->is_logged_in();
}
public function index() {
echo 'hello';
}
}
I only want to make function within the controller accessible if the user is logged in.
This is the helper which is autoloaded
$autoload['helper'] = array('url','array','html','breadcrumb','form','function','accesscontrol');
(accesscontrol_helper.php):
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page. <a href="../login">Login</a>';
die();
//$this->load->view('login_form');
}
}
Why would I not be able to run the function? Is containing the code in the helper the best method?
As other already mentioned, helpers are simply a collection of functions. Expanding on them:
You cannot, moreover, call a CI's class inside them without first instantiating the main CI object. This is a more proper way to use your helper function:
if(!function_exists('is_logged_in'))
{
function is_logged_in()
{
$CI =& get_instance();
$is_logged_in = $CI->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page. <a href="../login">Login</a>';
die();
}
}
}
I would also have it return instead of echo
, and move the die()
to the controller, but this is another story.
Helpers are just included functions, so you don't need to access it with $this
. Just call it as a normal function:
is_logged_in();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With