Friday, April 08 2016

How to Create Custom Helper in Codeigniter

In this  article we have explained about how to create custom Helper in Codeigniter. Helper is a group of functions but it is not a class.

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

if ( ! function_exists('sample_method'))
{
    function sample_method($var = '')
    {
        return $var;
    }   
}

Save this to application/helpers/. We shall call it “my_first_helper.php“.

The first line exists to make sure the file cannot be included and ran from outside the CodeIgniter scope. Everything after this is self explanatory.
In Controller:

$this->load->helper('my_first_helper');
echo sample_method('Hello World');

If you use this helper in a lot of locations you can have it load automatically by adding it to the autoload configuration file i.e. \application\config\autoload.php.

$autoload['helper'] = array('my_first_helper');

Always make use that the helper file name is appended with “_helper” otherwise you will get an error.

Share Your Thoughts

phpexpertise

I’m Blogger and Programming Blog, Tutorials, PHP, MySQL, jQuery, Laravel, Wordpress and Codeigniter