codeigniter - using helper in controller doesn't work

Viewed 35508

I need to use a function in multiple controllers. So I though about using a custom helper, but it seems I can't get it to work. (It works in the view, but I need it in the controller)

It gives me following Fatal Error:

Fatal error: Call to undefined method Developers::checkIfLoggedIn() in /application/controllers/developers.php on line 12

Is it a smart move to use a helper to use a function in multiple controllers, or should I do it otherwise.

Thanks in Advance,
Mark

EDIT:
Controller file:

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Developers extends CI_Controller
{
    public function __construct()
    {
         parent::__construct()
         $this->load->helper('form');
         $this->load->helper('url');
         $this->load->helper('login');

         //helper function
         checkIfLoggedIn($this->session->userdata('loggedIn'));
    }
}

Helper file:

if (!defined('BASEPATH')) exit('No direct script access allowed');

if (!function_exists('checkIfLoggedIn'))
{
    function checkIfLoggedIn($session_loggedIn)
    {
        $loggedIn = $session_loggedIn;
        if($loggedIn == false)
        {
            redirect('login/');
        }
    }
}

}

5 Answers

Helpers are the ideal way to declare global functions in codeigniter and what you are doing is correct. Following are just few points that will help you.

  • Load all helpers through single line instead of separate lines.

    $this->load->helper('form');
    $this->load->helper('url');
    $this->load->helper('login');
    $this->load->helper(array('form','url','login'));
    
  • If you want to make it global across all the controller files, then you can put it in the autoload.php file located in 'config/' directory. Update the $autoload['helper'] variable as follows:

    $autoload['helper'] = array('url','site');

Source: How to create & call global PHP functions in CodeIgniter

Related