CodeIgniter: Create new helper?
A CodeIgniter helper is a PHP file with multiple functions. It is not a class
Create a file and put the following code into it.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('test_method'))
{
function test_method($var = '')
{
return $var;
}
}
Save this to application/helpers/ . We shall call it "new_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.
Using the Helper
This can be in your controller, model or view (not preferable)
$this->load->helper('new_helper');
echo test_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. <your-web-app>\application\config\autoload.php
.
$autoload['helper'] = array('new_helper');
-Mathew
Some code that allows you to use CI instance inside the helper:
function yourHelperFunction(){
$ci=& get_instance();
$ci->load->database();
$sql = "select * from table";
$query = $ci->db->query($sql);
$row = $query->result();
}