183

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

Kuf
  • 15,678
  • 4
  • 61
  • 85
Jonathan
  • 8,146
  • 20
  • 64
  • 100

7 Answers7

385

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

Nam G VU
  • 28,311
  • 62
  • 206
  • 338
The Pixel Developer
  • 12,693
  • 9
  • 40
  • 59
  • 33
    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". – Bhumi Singhal Dec 11 '12 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 '13 at 09: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](http://ellislab.com/forums/viewthread/109584/P70). 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. – General Redneck Apr 26 '13 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 '14 at 09: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.** – Alejandro Iván May 15 '14 at 16:03
80

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();
}
Nic3500
  • 5,007
  • 10
  • 26
  • 33
r4ccoon
  • 2,786
  • 4
  • 23
  • 31
17

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

Mansukh Ahir
  • 3,546
  • 4
  • 36
  • 58
Eduardo Chavira
  • 896
  • 11
  • 7
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.

Community
  • 1
  • 1
lima
  • 720
  • 3
  • 8
  • 25
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.

Mansukh Ahir
  • 3,546
  • 4
  • 36
  • 58
Sumit
  • 111
  • 1
  • 6
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!
GAMITG
  • 3,670
  • 7
  • 30
  • 50
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'];