Libraries
Helpers are small function collections; libraries are classes; services create shared objects. Choosing the right one keeps repeated work out of controllers and views.
Built-in helpers
The URL helper provides base_url(), site_url(), and route_to(). The form helper builds fields and labels. The HTML helper escapes and formats output, and the security helper exposes CSRF tokens.
helper('url');
echo base_url('assets/css/app.css');
helper(['form', 'url']);
echo form_open('/contact');
Write a custom helper
<?php // app/Helpers/price_helper.php
if (! function_exists('format_price')) {
function format_price(float $amount): string
{
return '$' . number_format($amount, 2);
}
}
helper('price');
echo format_price(49.5);
Guard helper functions with function_exists() so they cannot be declared twice.
Libraries
A library encapsulates a feature such as an invoice calculator or an API client. Place it in app/Libraries under the App\Libraries namespace.
<?php
namespace App\Libraries;
class InvoiceTotals
{
public function withTax(float $subtotal, float $rate): float
{
return round($subtotal * (1 + $rate), 2);
}
}
$totals = new \App\Libraries\InvoiceTotals();
$total = $totals->withTax(200.0, 0.18);
Services
Services give you a central way to create and reuse objects. The framework's own services are available through service().
$request = service('request');
$session = service('session');
$logger = service('logger');
Third-party packages
Install Composer packages as usual and use their namespaces directly. Keep package-specific code behind a small library or service so the rest of the application does not depend on the package API.
Use a helper for one pure function, a library for stateful behaviour, and a service when the object should be shared across the request.