Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Helpers

A helper is a file with a set of plain functions on one subject: addresses, forms, text. Helper functions are called without objects or classes, which makes them especially handy in views. Built-in helpers live inside the framework, your own go to the app/Helpers folder.

Loading

A helper is loaded by name with the helper() function:

// app/Controllers/Posts.php
public function index(): string
{
    helper('text');
 
    return word_limiter('A very long text of the first blog post', 3);
}

The page prints the first three words and an ellipsis: "A very long…". The word_limiter() function belongs to the text helper and is unavailable before helper('text') is called.

The url helper

The url helper is always loaded — its functions can be called right away:

FunctionWhat it returns
site_url('posts/5')The full address of a page
base_url('css/app.css')The address of a file in the public folder
url_to('posts.show', 5)The address by route name
current_url()The address of the current page
anchor('posts', 'All posts')A ready link tag
url_title('Hello, world', '-', true)A string suitable for an address

An example in a view:

<!-- app/Views/partials/nav.php -->
<nav>
    <?= anchor('posts', 'All posts') ?>
    <a href="<?= site_url('posts/new') ?>">New post</a>
</nav>
<link rel="stylesheet" href="<?= base_url('css/app.css') ?>">

Both links get a full address like http://localhost:8080/posts. The base of the address comes from the app.baseURL setting described in the next lesson.

Automatic loading

To avoid calling helper() in every method, list the helpers you need in the $helpers property of the BaseController class:

// app/Controllers/BaseController.php
protected $helpers = ['form', 'text'];

Now the functions of these helpers are available in all controllers and their views.

Your own helper

Your own functions go to a file whose name ends in _helper.php. Create app/Helpers/blog_helper.php by hand:

// app/Helpers/blog_helper.php
function reading_time(string $text): string
{
    $words = count(preg_split('/\s+/u', trim($text)));
    $minutes = max(1, (int) ceil($words / 200));
 
    return "$minutes min read";
}

It is loaded the same way, by name without the ending: helper('blog'). After that a view can contain <?= reading_time($post['body']) ?>.

Other built-in helpers

NameWhat it is for
formForm tags and error output
textTrimming and processing text
numberFormatting numbers and file sizes
htmlTags for images, lists, styles
filesystemWorking with files and folders

Common mistake

The message "Call to undefined function" in a view almost always means the helper is not loaded. The functions old(), form_open(), word_limiter() do not exist until helper() is called with the right name. Add the helper to $helpers in BaseController and the error disappears on every page.

Thanks for reading!

Donate to the site — we work hard for you.