189

I need to loop lot of arrays in different ways and display it in a page. The arrays are generated by a module class. I know that its better not to include functions on 'views' and I want to know where to insert the functions file.

I know I can 'extend' the helpers, but I don't want to extend a helper. I want to kind of create a helper with my loop functions.. Lets call it loops_helper.php

2
  • Why can't you just pass those arrays to the view? Apr 29, 2009 at 22:07
  • I can, but that misses the point of sepparating the view from the functions..
    – Jonathan
    Apr 29, 2009 at 22:37

7 Answers 7

393

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

5
  • 36
    Always make use that the helper file name is appended with "_helper" otherwise you will get an error. So "helper_name" wont work but name your file "name_helper". Dec 11, 2012 at 10:06
  • 3
    As of CI2, you will also need to get the CI instance in order to use a helper within a model: $ci = get_instance(); $ci->load->helper(’name_helper’);
    – Evernoob
    Apr 24, 2013 at 9:36
  • 3
    Just a note, The helper doesn't have to be a function. It can be a class as well. For instance, check out the strategy to create "Widgets" over at EllisLab's Forum. Then you can use that class anywhere... also Techincally, you could load your helper into the CI instance if you desire to by doing getting the instance and then setting $this as a property of it... All if you want to of course. Apr 26, 2013 at 15:24
  • 2
    What is the use of the if function_exists check? Is it a code igniter thing, is it a general php good practice thing? Why would you need it?
    – skrln
    Apr 14, 2014 at 9:33
  • 2
    @skrln there's a chance that you have a helper auto-loaded (let's call it cool_helper) and, if you forget that and manually call $this->load->helper('cool_helper') after it was auto-loaded, you will get an "already defined" PHP error or something. This prevents from loading the same code twice (it's something like the include_once() PHP function but for CodeIgniter helpers, to avoid problems). Basically, translating a little: if function doesn't exist, it means the helper wasn't loaded before. Let's define it. May 15, 2014 at 16:03
82

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();
}
2
  • 1
    @r4ccoon, so right. Didn't even take me 5 mins to come back for the instance definitions. :) Dec 31, 2014 at 14:01
  • @r4ccoon, and that is a fantastic tip
    – Arun
    Mar 4, 2016 at 11:44
18

Well for me only works adding the text "_helper" after in the php file like:

Codeiginiter Helpers

And to load automatically the helper in the folder aplication -> file autoload.php add in the array helper's the name without "_helper" like:

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

And with that I can use all the helper's functions

2
  • 1
    I just discovered that like you said, CodeIgniter will require _helper at the end of the file name. May 30, 2013 at 20:48
  • @Jared, yes, it was also the case for me, it requires the _helper at the end of the file name!
    – pollux1er
    Sep 19, 2014 at 9:52
11

To create a new helper you can follow the instructions from The Pixel Developer, but my advice is not to create a helper just for the logic required by a particular part of a particular application. Instead, use that logic in the controller to set the arrays to their final intended values. Once you got that, you pass them to the view using the Template Parser Class and (hopefully) you can keep the view clean from anything that looks like PHP using simple variables or variable tag pairs instead of echos and foreachs. i.e:

{blog_entries}
<h5>{title}</h5>
<p>{body}</p>
{/blog_entries}

instead of

<?php foreach ($blog_entries as $blog_entry): ?>
<h5><?php echo $blog_entry['title']; ?></h5>
<p><?php echo $blog_entry['body']; ?></p>
<?php endforeach; ?>

Another benefit from this approach is that you don't have to worry about adding the CI instance as you would if you use custom helpers to do all the work.

3

Create a file with the name of your helper in /application/helpers and add it to the autoload config file/load it manually.

E.g. place a file called user_helper.php in /application/helpers with this content:

<?php
  function pre($var)
  {
    echo '<pre>';
    if(is_array($var)) {
      print_r($var);
    } else {
      var_dump($var);
    }
    echo '</pre>';
  }
?> 

Now you can either load the helper via $this->load->helper(‘user’); or add it to application/config/autoload.php config.

3

Just define a helper in application helper directory then call from your controller just function name like

helper name = new_helper.php
function test_method($data){
 return $data
}   

in controller load the helper

$this->load->new_helper();
$result =  test_method('Hello world!');
if($result){
 echo $result
}

output will be

Hello World!
3

To retrieve an item from your config file, use the following function:

$this->config->item('item name'); Where item name is the $config array index you want to retrieve. For example, to fetch your language choice you'll do this:

$lang = $this->config->item('language'); The function returns FALSE (boolean) if the item you are trying to fetch does not exist.

If you are using the second parameter of the $this->config->load function in order to assign your config items to a specific index you can retrieve it by specifying the index name in the second parameter of the $this->config->item() function. Example:

// Loads a config file named blog_settings.php and assigns it to an index named "blog_settings"

$this->config->load('blog_settings', TRUE);

// Retrieve a config item named site_name contained within the blog_settings array

$site_name = $this->config->item('site_name', 'blog_settings');

// An alternate way to specify the same item:

$blog_config = $this->config->item('blog_settings');

$site_name = $blog_config['site_name'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.