Helpers & Libraries

So far in this track, every feature you've touched — routing, controllers, views, models — has been part of CodeIgniter's core MVC flow. But a huge amount of the day-to-day usefulness of any framework comes from smaller supporting tools that sit alongside that flow: little utility functions for common jobs, and bigger reusable classes for heavier lifting. CodeIgniter splits these into two distinct concepts with two distinct philosophies: Helpers and Libraries. Understanding the difference — and knowing when to reach for which — will save you from reinventing things the framework already gives you for free.

1. What Is a Helper?

A Helper in CodeIgniter is simply a file full of ordinary, standalone PHP functions. They are not classes, they carry no state, and they aren't tied to any object. Each helper file groups together functions related to one purpose — URLs, forms, strings, arrays, and so on — and once a helper is loaded, every function inside it becomes a plain global function you can call directly, in a controller or straight from a view.

HelperWhat it provides
url_helpersite_url(), base_url(), current_url(), anchor() — building links and absolute URLs
form_helperform_open(), form_input(), form_label(), form_close() — generating form markup
text_helperword_limiter(), character_limiter(), ascii_to_entities() — string manipulation for display
array_helperarray_deep_search(), array_flatten() and other array utilities
html_helperShortcuts for common HTML tags such as lists and images

2. Loading a Helper

Helpers are not loaded automatically by default (with a couple of exceptions the base controller already loads for you), so you call the global helper() function to pull one in before you use its functions — typically at the top of a controller method, or in the controller's constructor if every action needs it:

<?php

namespace App\Controllers;

class Pages extends BaseController
{
    public function contact()
    {
        helper('url');

        $data['homeLink'] = site_url('/');
        return view('pages/contact', $data);
    }
}

You can load several helpers at once by passing an array, which is the more common real-world pattern:

helper(['url', 'form', 'text']);

In practice, you rarely need to type this in every single controller. CodeIgniter's app/Controllers/BaseController.php declares a $helpers property that every controller extending it inherits, so many projects simply list the helpers they use everywhere once, right at the top:

protected $helpers = ['url', 'form'];
Tip: Helper functions are plain global functions, which also means they are automatically available inside your views — no extra loading step is needed there, as long as the helper was loaded before the view renders.

3. Writing a Custom Helper

When none of the built-in helpers cover something you do repeatedly — formatting a price, turning a status code into a readable label, generating a slug — you write your own. Custom helpers live in app/Helpers/ and follow a simple naming convention: a file named app_helper.php exposes an "app" helper you load with helper('app').

// app/Helpers/app_helper.php
<?php

if (!function_exists('format_price')) {
    function format_price(float $amount): string
    {
        return '$' . number_format($amount, 2);
    }
}

Wrapping the definition in function_exists() is a defensive habit borrowed from CodeIgniter's own helpers — it prevents a fatal "cannot redeclare function" error if the helper file is ever accidentally loaded more than once. Once saved, use it exactly like a built-in helper:

helper('app');
echo format_price(19.9); // $19.90

4. What Is a Library?

Where a Helper is a bag of loose functions, a Library is an ordinary object-oriented class — something you instantiate, that can hold internal state, accept configuration, and expose methods that work together as a cohesive unit. CodeIgniter ships a number of built-in libraries covering the kind of substantial jobs that don't fit neatly into a single function call:

LibraryWhat it's for
SessionPersisting data across requests for a single visitor — covered in depth on the next-but-one page
EmailComposing and sending email through SMTP, sendmail, or PHP's mail()
ImageResizing, cropping, watermarking, and otherwise manipulating uploaded images
ValidationRule-based validation of form and API input — the subject of the very next page
PagerGenerating pagination links for large result sets

5. Helper vs. Library: The Core Difference

It's worth pausing on this distinction, because it explains a lot about how the rest of CodeIgniter is organized. The short version: a Helper is a function, a Library is a class.

HelperLibrary
ShapePlain functions in a fileA class you instantiate
StateStateless — no memory between callsOften stateful — can hold configuration, connections, or data
Loadinghelper('name')Constructor injection, or a service factory such as Config\Services
Good fit forSmall, single-purpose utility tasksLarger, multi-step jobs with internal logic
Examplebase_url()Session, Email, Validation
Note: Neither approach is "better" — they solve different sized problems. If you find yourself passing more and more arguments into a helper function just to track state between calls, that's usually a sign the job has outgrown a Helper and belongs in a Library (or a Model) instead.

6. Loading a Built-in Library via Services

CodeIgniter 4's core libraries aren't loaded with a helper()-style call. Instead, CI4 wires up its internal components through a factory class, Config\Services, following what's usually called the service locator pattern. Every core library has a corresponding method on Services that returns a ready-to-use instance:

$session = \Config\Services::session();
$session->set('visits', 1);

For the handful of services used constantly — sessions especially — CodeIgniter also exposes a plain global helper function as a shortcut, so you'll see both styles in real code and documentation:

session()->set('visits', 1); // identical result, shorter to type

Using Services instead of directly writing new Session(...) everywhere has a real benefit: CodeIgniter can return the exact same shared instance across your whole request when that makes sense, and it makes it possible to swap in a different implementation (for example, in tests) without touching the code that consumes the service. You'll see this exact pattern again on the very next page, where the Validation service does the heavy lifting behind form validation, and on the page after that, where Config\Services::session() is how session data gets set, read, and removed.

Next steps: With Helpers and Libraries in your toolbox, head to Form Validation to see CodeIgniter's Validation library used properly — defining rules, checking results, and displaying errors back to the user.