11

I am getting little bit confused, the way the methods of library and helper are used in code igniter. I am still learning code igniter.

CONTROLLER

function index(){
    $this->load->helper('text');
    $this->load->library('auth'); //custom library

    $data['string'] = 'this is sample ..... this is sample';
    $this->load->view('article', $data);
}

VIEW

<?php 
if(is_logged_in()){    //is_logged_in() is the method from the library, 'auth'
    echo 'You are logged in';
}
<p><?php echo word_limiter($string, 10); ?></p> <!--word_limiter() is the method from the helper, 'text' -->

In the above view file, the helper method word_limiter() works fine. But the method is_logged_in() does not work. But if I do ($this->auth->is_logged_in()), it will work.

But why the method from helper i.e. word_limiter() does not have to be written like this ($this->text->word_limiter()).

Is there a difference between the method of helper and library are called upon ?

2 Answers 2

28

A CodeIgniter helper is a set of related functions (Common functions) which you could use them within Models, Views, Controllers,.. everywhere.

Once you load (include) that file, you can get access to the functions.

But a Library is a class, which you need to make an instance of the class (by $this->load->library()). And you'll need to use the object $this->... to call the methods.

As a thumb rule: A library is used in object oriented context (Controller, ...), while a helper is more suitable to be used within the Views (non object oriented).

3

CI Helper may or may not have class

But Library must have class representation.

Refer this SO Answer

CodeIgniter: Decision making for creating of library & helper in CodeIgniter

1
  • 2
    yea, that link provided me with a more clarification. Feb 10, 2014 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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