When to use a helper and when to use a library

Updated Jun 7, 2020・1 minute read Post By Tony Lea

Using Codeigniter there are two main types of references you can use in conjunction with the codeigniter framework. These two include 'libraries' and 'helpers'. A library is a specific object that can be loaded and used inside of your code. A few examples of libraries include the database library, pagination library, form validation library, and many others. A helper class is a set of functions. These helper functions can help a library or any other type of function that you want to use over and over again in your code.

In short... A Library is an object which can store variables, data, and functions; whereas, a Helper is a class that only contains functions.

Here are the definitions of these two types of references:

libraries: Utility classes where object state is important (payment gateways, authentication, etc.)

helpers: Collections of related functions (not classes) that do repetitive tasks (strings, arrays, etc.)

Let's put this into a real world scenario. A poker game. If you were to build a poker game you would use a library to create 'the deck of cards' maybe you would call this library 'cards'. In this library object you would contain the array of cards and an assortment of functions such as 'shuffle', 'deal', 'get_card', and many other card related functionalities. Now, lets say you wanted to create a function such as 'game_over', 'game_start', or 'game_tie'... in this case you may want to create a 'helper' called 'game_status_helper' which contain these functions which return the status of the game. This is just one simple example of using libraries as opposed to helpers. If you still are having trouble deciding which one you should use, you can checkout the full Codeigniter user guide at http://www.codeigniter.com/user_guide/.

The following is an example of a Sample Library:

<?phpif ( ! defined('BASEPATH')) exit('No direct script access allowed');class SampleLibrary{

	var $var1		= '';
	var $var2		= 'data';
	function function1($arguments){

And the following is an example of a Sample Helper:

<?phpif ( ! defined('BASEPATH')) exit('No direct script access allowed');
	if ( ! function_exists('helper_function'))
	function helper_function($argument = ''){
		//Perform functionality	}

© 2020 DevDojo LLC. All rights reserved.