Helpers are files of simple functions for common tasks. Load them before use.
Loading helpers
- In a controller:
helper('form');orhelper(['form', 'text']); - For every controller: add them to
protected $helpers = ['form', 'url'];inBaseController
URL helper (always loaded)
base_url('css/style.css')— link to files inpublicsite_url('posts')— link to a routeurl_to('posts')— URL of a named routecurrent_url(),previous_url()anchor('posts', 'All posts')— a full<a>tag
Form helper
form_open('posts/save')— opening<form>tag, adds the CSRF field automatically when CSRF is onform_input(),form_dropdown(),form_close()set_value('title')— refill a field after a failed submit
Other helpers
text (word_limiter, character_limiter), number (number_to_currency), date, filesystem, cookie, inflector.
Your own helper
Create app/Helpers/site_helper.php with plain functions, then load it with helper('site').
Example
Example — Custom helper and URL helpers
PHP
<?php
// app/Helpers/site_helper.php
if (! function_exists('rupees')) {
function rupees(float $amount): string
{
return '₹' . number_format($amount, 2);
}
}
// app/Controllers/BaseController.php
protected $helpers = ['form', 'text', 'site'];
// In any view:
// <link rel="stylesheet" href="<?= base_url('css/style.css') ?>">
// <?= anchor('posts', 'All posts') ?>
// <p>Price: <?= rupees(1499) ?></p>
// <p><?= word_limiter($post['body'], 20) ?></p>
rupees(1499) prints ₹1,499.00. anchor() prints <a href="http://localhost:8080/posts">All posts</a>. word_limiter() shortens the text to 20 words.