Bhupal Sapkota Computer Programmer Unraveling art, science, and commerce behind technology. Passionate about teaching web/mobile programming, writing, and growing an online business.

Bhupal's Newsletter

If you want early access and opportunities that I don’t post publicly, get on my email list.

Home

CodeIgniter Helpers – How to write your own?

Find yourself again and again doing CI or are you just getting started in to your next big project ? Get this book by Rob Foster. This is an easy-to-follow guide consisting of a number of projects that enable you to develop full-featured applications at a fast pace. CodeIgniter Web Application Blueprints

What is here:
         -> What is a codeigniter helper? an example
         -> Creating your own codeigniter helper, create a helper which will have a function to Check Ajax requests
         -> Accessing sessions/models from within Helpers
         -> A tip on how to load codeigniter models from within another model.

From CI site

Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc.

A helper can be loaded anywhere within your controller functions (or even within your View files, although that’s not a good practice), as long as you load it before you use it.

Let me give you and example:

in controller, model or view you have to first load the helper you want to use with following line:
$this->load->helper(‘name‘);
where ‘name’ === is helper file residing in ===>  application/helpers/name_helper.php (custom helper if exists)
or system/helpers/name_helper.php (bundled with codeigniter)

name’ is the name you want for your helper, then a _ (underscore) & helper.php, the codeigniter’s way.

if you want to look at a sample: go check system/helpers folder, they come bundled with codeigniter. Here’s a snippet from: system/helpers/url_helper.php
<?php  if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);

if ( ! function_exists(‘site_url’))
{
    function site_url($uri = ”)
    {
        $CI =& get_instance();
        //every time you need to use codeigniter system libraries or functions or model you’d do this      through the get_instance
        return $CI->config->site_url($uri);       
    }
}

Remember, when you used this site_url() function?? okay what you did was:
loaded the helper at your controller construction or where ever you needed using,  $this->load->helper(‘url‘);and simply echo site_url(); or like that. 

How to write your own helper  : Check Ajax Request using Codeigniter Helper

Yesterday, while going through my current project, I was calling lots of controller actions with jQuery Ajax and i was in need to check whether the call/request is made through Ajax or not in the controllers. Since i needed a way to use this facility in lots of controllers, i thought helpers would come handy here.

Rather than just copy/pasting the same lines of code in every controllers or at times you may need to use same functions in models & views too, it is good practice to make this function have some separate space in helpers (but not a good practice to load helper in views, see above, from CI site). So you should be clear at first whether your function need a place in helper or not??? Ask yourself  and decide for your work, if the frequency of your function call is going to be maximum, sure create a new helper or extend existing one. I decided to create one in my case.
Okay let’s make our Ajax request checker?? isAjax() function, residing in useful helper. When i Googled around for checking Ajax request i found a three line snippet here CHECK FOR AJAX REQUEST, i’ll will be implementing this for our purpose here. It goes like this:

function isAjax() {
return (isset($_SERVER[‘HTTP_X_REQUESTED_WITH’]) &&
($_SERVER[‘HTTP_X_REQUESTED_WITH’] == ‘XMLHttpRequest’));
}

The Helper:

system/application/helpers/useful_helper.php
<?php if (!defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
//secure your snippet from external access
function isAjax() {  
           return ( isset($_SERVER[‘HTTP_X_REQUESTED_WITH’]) && $_SERVER[‘HTTP_X_REQUESTED_WITH’] == ‘XMLHttpRequest’);  
      }
?>

Using in Controller: application/controllers/somecontroller.php

function submit_form(){
//function you call when you submit your form through Ajax. 
$this->load->helper(‘useful’); //load our just defined helper
if(isAjax()){
          echo ‘The request is made throug ajax. success!’ ;
          //do your stuffs
          exit;

       }     

}

 
Accessing session/models from within Helpers

<?php if (!defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
      function isAjax() {  
           return ( isset($_SERVER[‘HTTP_X_REQUESTED_WITH’]) && $_SERVER[‘HTTP_X_REQUESTED_WITH’] == ‘XMLHttpRequest’);  
      }
     function check_login(){     
      //$userId = $this->session->userdata(‘userid); this line will not work here <<—–
       // you’d access your session variables through get_instance() as below
       $CI =& get_instance();
       //now session access through this instance
       $userId = $CI->session->userdata(‘userid);
       if ($userid < 0 ) {
              return 0; //user not logged in
           }
      else {
             return 1; user session exists, must be logged in 
           }
      }
  function hello_model_world(){     
        //or if you decided to load & use you models here
        //$this->load->model(‘Hello_model’);   <—- this will not work too.
        //use as 
         $CI =& get_instance(); //first get instance
         $CI->load->model(‘Hello_model’);  //then load model through instance.  
         //and calling a model function
         $data = $CI->Hello_model->display_this(‘hello world!’);
        //assuming your model returns capitalizing the initial letters of the words
         return $data; //will give Hello World! 
      }
?>

Now, you can easily load your helper in controllers & models and use it as regular helpers.

Extra tip about loading codeigniter model from another models:

You see how handy the $CI =& get_instance(); is in helpers. okay, let me add a quick tips talking about this, what if at times you needed to find out a way to load another models in your current model?? Ok here’s the solution:

<?php
class Test_model extends Model {
function Test_model()
    {
        //Call the Model constructor
        parent::Model();
    }
function do_something(){
//you wanted to load another model called Hello_model here in this function in this model class
//it’s okay
//use
         $CI =& get_instance(); //first get instance
         $CI->load->model(‘Hello_model’); //then load model
         $data = $CI->Hello_model->display_this(‘hello world!’); //call functions
         //do anything with this $data        
}
}
?>

Happy Coding.
Regards

Category: technology
Tagged with:

Copy & Share

CodeIgniter Helpers – How to write your own?
https://bhupalsapkota.com/codeigniter-helpers-how-to-write-your-own/

Your thoughts? Please leave a comment

Your email address will not be published. Required fields are marked *