How to create custom helpers in CodeIgniter
In this article, We will discuss how to create a custom helpers and use in CodeIgniter. CodeIgniter allows the creation of custom helpers. So we can easily create a custom helper. we will take the latest example and learn how to use a custom helper in CodeIgniter. so let’s follow the below step.
Step 1: Create the helper file.
first, we will create a helper file in the “application/helpers/commonfunction_helper.php”. put some code in this file. here this file. we will get the student all detail using the custom helper function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* * get_all_rows * */ function get_all_student_rows() { $CI =& get_instance(); $CI->db->select(); $query = $CI->db->get('students'); //echo $CI->db->last_query();die; return $query->result_array(); // This will return array } ?> |
Step 2: Load The Custom helper
Now, we will load the custom helper so we will open the application/config/autoload.php file and add the helper name in the helper array.
1 2 3 4 5 6 7 8 9 | /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('commonfunction_helper'); |
Step 3: How to use the custom helper function in Controller or Views.
now, we can use the custom helper function in Controller or Views. we can get the student detail in Controller or Views using the call get_all_rows helper function.
Controller Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Student extends CI_Controller { function __construct() { parent::__construct(); } public function index() { $student_detail = get_all_student_rows(); echo "<pre>"; print_r(student_detail); echo "</pre>"; } } |
View Example
1 2 3 4 5 6 | <?php $student_detail = get_all_student_rows(); echo "<pre>"; print_r(student_detail); echo "</pre>"; ?> |
So finally, I hope you like this article.