Hello Readers,
I hope you all are doing well!
This blog is about to create custom helper in Codeigniter(CI).
Before we start, we need to understand the definition of Helper and Library in CI.
Helper: Helper contains setup of functions which you can directly access in Model, View, Controllers without creating an object/instance.
E.g URL, Text, Cookie etc. are helpers. More: https://codeigniter.com/user_guide/general/helpers.html
Library: Library is a class and we need to create an object before using it.
E.g. Session, Email etc. are libraries. More: https://codeigniter.com/user_guide/general/libraries.html
E.g. Session, Email etc. are libraries. More: https://codeigniter.com/user_guide/general/libraries.html
How to create custom helper in CI?
- Create PHP file in %Project Directory%/application/helpers/ (You can also create helper file in system directory but it’s not the right way.)
- You can give an identical name to that file. E.g. auth_helper.php (You have to add _helper as a suffix.)
- Add following code to that file
- <?php
defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);
function isLogin() {
$CI = & get_instance();
if ($CI->session->userdata(‘admin_id’)) {
return true;
}
return false;
} - If you want to access CI library/model in custom helper then you have to access via instance.
E.g. &get_instance(); - In above example, I created login check function. This will check whether user is logged in or not.
How to use in CI controllers, view, model etc.?
- First, you need to load helper. You can load in multiple ways.
- Autoload: Please add helper’s name in autoload.php in the config directory of the project.
Please review this link http://prntscr.com/irhgro - Manually : You can add helper using $this->load->helper(‘name_of_helper’);
- Autoload: Please add helper’s name in autoload.php in the config directory of the project.
- You can now simply access all the functions of helpers. Just need to write down the name of a function.
E.g.
if (isLogin()) {
echo “Logged in”;
}else{
echo “Not Log in”;
} - In above exmaple, isLogin() is the name of function from auth helper.
- You can add function anywhere you want to use.
I hope you understand this tutorial. If you have any questions or confusion then please comment it.
Leave a Reply