Helper Functions
Relevant source files
The following files were used as context for generating this wiki page:
Helper functions in CodeIgniter 4 are collections of stateless, procedural functions designed to assist with specific tasks. Unlike classes, they do not require instantiation and are globally available once loaded. Each helper file is a simple group of functions focused on a particular category, such as generating URL strings, creating form elements, or manipulating text. This approach provides a lightweight and straightforward way to reuse common logic throughout an application without the overhead of class-based structures.
The framework comes with a variety of built-in helpers, but it also provides a simple mechanism for developers to create their own custom helpers or extend the existing ones. This makes the helper system a flexible tool for building a reusable function library tailored to an application's specific needs.
Sources: source/general/helpers.rst:3-7
Loading Helpers
A helper file must be loaded into memory before its functions can be used. This can be done in several ways, providing flexibility for different use cases, from on-demand loading within a controller method to autoloading for application-wide availability.
Sources: source/general/helpers.rst:14-15
Loading Methods
There are two primary methods for loading helpers: manually on-demand or automatically at application startup.
-
Manual Loading: The
helper()function can be called anywhere to load a specific helper file. You can pass a single helper name or an array of names. The.phpextension and "_helper" suffix are not needed.// Load a single helper helper('url'); // Load multiple helpers helper(['url', 'form', 'text']);Sources: source/general/helpers.rst:22-31
-
Auto-loading: To make a helper's functions globally available on every request, it can be added to the
$helpersarray in theapp/Config/Autoload.phpfile.// app/Config/Autoload.php public $helpers = ['url', 'form'];Sources: source/general/helpers.rst:33-40
The following diagram illustrates the decision process for loading a helper.
This diagram shows the two paths for making helper functions available: autoloading for global use or manual loading for specific cases.
Sources: source/general/helpers.rst:14-40
Core Helper Overview
CodeIgniter 4 includes a set of core helpers to handle common development tasks. The table below summarizes some of the key helpers available.
| Helper Name | Description |
|---|---|
array | Provides functions for working with arrays. |
cookie | Simplifies working with cookies. |
date | Assists with common date-related tasks. |
filesystem | Provides functions for working with the file system. |
form | Contains functions that help create web forms. |
html | Assists in building standards-compliant HTML. |
inflector | Contains functions to change word case (e.g., plural to singular). |
number | Helps format numbers in various ways (e.g., currency). |
security | Provides security-related functions like XSS filtering. |
text | Contains various text formatting and manipulation functions. |
url | Assists in creating and formatting URLs. |
xml | Provides tools for working with XML data. |
Sources: source/general/helpers.rst:9-11, source/helpers/array_helper.rst, source/helpers/form_helper.rst, source/helpers/security_helper.rst, source/helpers/url_helper.rst
Detailed Helper Examples
URL Helper
The URL Helper provides functions for creating and managing URLs within the application, ensuring they are portable and correctly formatted based on the application's configuration.
Sources: source/helpers/url_helper.rst:3-4
Key functions include:
site_url(): Creates a full URL based on your site'sbaseURLconfiguration. It will append any URI segments passed to it.base_url(): Returns the site's base URL, as defined inapp/Config/App.php.current_url(): Returns the full URL of the page currently being viewed, including any query string.anchor(): Generates a standard HTML anchor link tag (<a>) based on the local site URL.
The anchor() function is particularly useful for creating internal links.
| Parameter | Type | Description |
|---|---|---|
$uri | string | The URI string for the link's href. |
$title | string | The text for the link. If empty, the URI is used. |
$attributes | mixed | A string or array of attributes to add to the <a> tag. |
Sources: source/helpers/url_helper.rst:14-100
Form Helper
The Form Helper contains functions that assist in creating HTML forms. It is particularly powerful when used with the Validation Library as it can automatically repopulate form fields with submitted data and display validation errors.
Sources: source/helpers/form_helper.rst:3-6
A typical form creation flow involves form_open(), various input helpers, and form_close().
This graph shows the sequence of helper calls to build a complete HTML form.
Sources: source/helpers/form_helper.rst:14-100
Key functions:
form_open(): Creates an opening<form>tag with the site'sbaseURLautomatically added. It also adds a hidden CSRF field if enabled.form_input(): Creates a standard<input type="text">field. It accepts an array of attributes.set_value(): A companion function used in thevalueattribute of an input to repopulate the field with submitted data after a validation failure.form_close(): Creates the closing</form>tag.
Sources: source/helpers/form_helper.rst:14-26, 68-76, 303-311
Security Helper
The Security Helper provides functions for handling data securely, primarily focused on preventing Cross-Site Scripting (XSS) attacks.
Sources: source/helpers/security_helper.rst:3-4
The most important function in this helper is esc().
esc($data, $context = 'html'): This function performs context-aware escaping of output data. It is a wrapper around the Kint library and is crucial for preventing XSS vulnerabilities. The$contextparameter can be 'html', 'js', 'css', 'url', or 'attr'.
The following diagram shows how esc() mitigates an XSS attack.
This sequence demonstrates that by escaping the malicious input, the script is not executed by the browser, thus preventing the attack.
Sources: source/helpers/security_helper.rst:14-36
Array Helper
The Array Helper provides functions for more convenient array manipulation.
Sources: source/helpers/array_helper.rst:3-4
dot_array_search(string $search, array $values): This function allows you to inspect a multi-dimensional array using "dot notation" for keys. It's useful for fetching a specific value from a complex array structure without writing nestedisset()checks. For example,dot_array_search('user.name.first', $data)would access$data['user']['name']['first'].
Sources: source/helpers/array_helper.rst:14-29
Extending and Creating Helpers
CodeIgniter allows you to both extend existing helpers and create your own.
Extending Helpers: To add functionality to an existing helper (e.g., the URL Helper), create a file named app/Helpers/url_helper.php. Any functions you define in this file will be available alongside the original helper's functions. The system first looks for a helper in app/Helpers/, and if it doesn't exist, it loads the core system helper.
Creating New Helpers: To create a new helper, simply create a new file in your app/Helpers/ directory (e.g., app/Helpers/my_awesome_helper.php). The file should contain one or more global functions. You can then load this helper like any other using helper('my_awesome_helper').
Sources: source/general/helpers.rst:42-63, source/contributing/styleguide.rst:214-216
The process for creating and using a custom helper is as follows:
This flowchart outlines the steps from file creation to function usage for a custom helper.
Sources: source/general/helpers.rst:54-63
Summary
Helper functions are a fundamental part of CodeIgniter 4 development, offering a simple and efficient way to manage common, reusable procedural code. They cover a wide range of functionalities from URL and form generation to security and data manipulation. The ability to load them on-demand or globally, combined with the straightforward mechanism for creating custom helpers, makes them an indispensable tool for keeping application code clean, organized, and DRY (Don't Repeat Yourself).
Sources: source/general/helpers.rst:3-7