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 ?
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.
To use helper files, you need to load it. Once loaded it is globally available to your controller and views. They are located at two places in CodeIgniter. CodeIgniter will look first for a helper in application/helpers folder and if not found there then it will go to system/helpers folder.
Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With