Ad Code

Ticker

6/recent/ticker-posts

How to create custom helper in codeigniter


In the codeigniter have already many helper in system folder but some time require single function almost every function like slugify function. In the codeigniter helper function is same as a php function same as write in codeigniter helper with the usage of codeigniter helper structure like this example,

The helper file created inside helper folder inside application folder


inside helper folder set the file name based on codeigniter structure helper file name

for example create a basic function for demo function for helper name is common then the file name is

common_helper.php

this file accessible via common name other string considered as codeigniter system file like helper and find inside helper folder.

Creating function inside helper
Before creating any function set if condition to check already initialize same function within projects then it will not accrued errors. for example,

if(!function_exists('my_function')){
    // my_function is defined
}

inside this function write your own code with function name like my_function because this is verify if already initialize any function with same name it doesn't initialize within project running environment.

if(!function_exists('my_function')){
    // my_function is defined
    function my_function(){
      //function logic and operations
    }
}

How to initialize and use custom helper functions

If you are want to initialize globally for all pages then you can call inside config/autoload.php file for globally calling.


Otherwise you can call inside controller function which you have to required usase of helper functions. Inside controller function call usage codeigniter helper calling refrence function.

$this->load->helper('common'); 

After calling this function you can use inside this function view page or controller function calling via function name of helper functions.

example;

my_function();

In the helper function you can call the codeigniter innstance and access codeigniter basic functions like db and library and models etc. Helper file also you can define argument of function and when you call then pass arguments.

Post a Comment

0 Comments

Ad Code