One of my CodeIgniter Controller functions needs to call a recursive function as part of its functionality. The function call chokes if I put it inside the controller class, and it can't access database functions ($this->db->get())
if I put it outside the class. Would making it a helper function fix this problem?
They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions. CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it becomes globally available in your controller and views.
The main difference between Helper and Library in CodeIgniter is that Helper is a file with a set of functions in a particular category and is not written in Object Oriented format, while the Library is a class with a set of functions that allows creating an instance of that class and is written in Object Oriented ...
A helper function is a function that performs part of the computation of another function. Helper functions are used to make your programs easier to read by giving descriptive names to computations. They also let you reuse computations, just as with functions in general.
You can get instance:
$CI =& get_instance();
After that you will be able to use $CI->db
for queries..
If you want to use $this in libraries, helpers, and access all the methods:
$this->ci =& get_instance();
$this->ci->load->database();
You can do also:
$this->ci->config->item('languages');
or
$this->ci->load->library('session');
We can define a function in helper
if (!function_exists('getRecordOnId'))
{
function getRecordOnId($table, $where){
$CI =& get_instance();
$CI->db->from($table);
$CI->db->where($where);
$query = $CI->db->get();
return $query->row();
}
}
and we can call from view like
$recordUser = getRecordOnId('users', ['id' => 5]); //here 5 is user Id which we can get from session or URL.
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