v1.0
Docs / Helpers

Helper Functions

Available helper functions for common tasks. Load helpers in BaseController or via app/Config/Autoload.php.

Table of Contents

  1. Loading Helpers
  2. Component Helper
  3. Format Helper
  4. RBAC Helper
  5. Upload Helper
  6. Media Helper
  7. Logger Helper

1. Loading Helpers

Autoload (Recommended)

File: app/Config/Autoload.php

public $helpers = [
    'component',
    'format',
    'rbac',
    'upload',
    'media',
    'logger',
];

In Controller

helper(['format', 'rbac']);

2. Component Helper

Functions for rendering view components.

FunctionDescription
component($name, $data)Render a component from Shared/Components
ajax_component($name, $data, ...)Render with AJAX refresh capability
is_active_route($pattern)Check if current route matches pattern
module_asset($module, $path)Get module asset URL

Examples

// Render shared component
<?= component('sidebar') ?>

// Render module-specific component
<?= component('Notification/item', ['notification' => $notif]) ?>

// Render from different module
<?= component('Web:header') ?>

// AJAX component with auto-refresh
<?= ajax_component('notification_bell', [], true, 'notif-bell', 30000) ?>

// Check active route for nav highlighting
<li class="<?= is_active_route('/admin/users') ? 'active' : '' ?>">

3. Format Helper

Date, time, and relative formatting functions.

FunctionOutput Example
formatDate($date)10 Jan 2025
formatDateTime($date)10 Jan 2025 12:10 (WIB)
formatDateTimeShort($date)10 Jan 12:10
formatTime12($date)10:12 AM
formatTime24($date)13:12
formatRelative($date)2 hours ago, Yesterday
formatDateRange($start, $end)10 Jan - 15 Jan 2025

Examples

// All functions accept various inputs
$date = '2025-01-10 12:30:00';  // string
$date = new DateTime();          // object
$date = 1704816000;              // timestamp

echo formatDate($date);           // "10 Jan 2025"
echo formatDateTime($date);       // "10 Jan 2025 12:30 (WIB)"
echo formatRelative($date);       // "Just now" or "2 hours ago"

// Date range
echo formatDateRange('2025-01-10', '2025-01-15');  // "10 - 15 Jan 2025"

4. RBAC Helper

Permission checking and menu building.

FunctionDescription
can($permission)Check if user has permission
canAny([$perms...])Check if user has ANY of the permissions
canAll([$perms...])Check if user has ALL permissions
userPermissions()Get all user permissions array
userRole()Get user's Role entity
userMenu($module)Get navigation menu for module

Examples

// Simple permission check
if (can('users.create')) {
    echo '<a href="/admin/users/create">Add User</a>';
}

// Check multiple permissions
if (canAny(['reports.view', 'reports.export'])) {
    echo 'Show reports section';
}

if (canAll(['orders.view', 'orders.edit', 'orders.delete'])) {
    echo 'Full order management access';
}

// In Blade-style views
<?php if (can('users.delete')): ?>
    <button>Delete User</button>
<?php endif; ?>

// Get role info
$role = userRole();
echo $role?->name;  // "Administrator"

// Build navigation menu
$menus = userMenu('admin');
foreach ($menus as $menu) {
    echo $menu->name;
}

5. Upload Helper

File upload with validation, compression, and thumbnail generation.

FunctionDescription
upload_file($file, $options)Upload any file with validation
upload_image($file, $options)Upload image with compression/resize
compress_image($path, $quality)Compress existing image
resize_image($path, $w, $h)Resize image maintaining ratio
convert_to_webp($path)Convert image to WebP format
generate_thumbnail($path)Generate thumbnail for image/PDF
get_file_preview($path)Get preview URL (thumb or icon)
delete_uploaded_file($path)Delete file and its thumbnails

Examples

// Upload any file
$file = $this->request->getFile('document');
$result = upload_file($file, [
    'directory' => 'uploads/documents',
    'maxSize' => 10 * 1024 * 1024,  // 10MB
    'allowedTypes' => ['pdf', 'doc', 'docx'],
]);

if ($result['success']) {
    $path = $result['path'];  // "uploads/documents/abc123.pdf"
}

// Upload image with compression
$result = upload_image($file, [
    'directory' => 'uploads/photos',
    'quality' => 80,
    'maxWidth' => 1920,
    'maxHeight' => 1080,
    'convertToWebp' => true,
]);

// Get file preview
$previewUrl = get_file_preview($result['path']);
// Returns thumbnail for images, icon for documents

// Delete file
delete_uploaded_file($path);  // Removes file + thumbnail + webp

6. Media Helper

Optimized image serving with format fallback.

FunctionDescription
picture($src, $alt, $attrs)Generate <picture> with format fallback
image_srcset($src, $widths)Generate srcset for responsive images
optimized_image_url($src)Get best available format URL

Examples

// Generate picture element with fallbacks
<?= picture('/uploads/hero.jpg', 'Hero image') ?>

// Output:
// <picture>
//   <source srcset="/uploads/hero.jxl" type="image/jxl">
//   <source srcset="/uploads/hero.webp" type="image/webp">
//   <img src="/uploads/hero.jpg" alt="Hero image" loading="lazy">
// </picture>

// With custom attributes
<?= picture('/uploads/photo.jpg', 'Photo', ['class' => 'rounded', 'width' => 400]) ?>

// Get optimized URL (returns JXL/WebP if available)
$url = optimized_image_url('/uploads/photo.jpg');
// Returns "/uploads/photo.jxl" if exists, else original

7. Logger Helper

Enhanced logging with custom levels and formatting.

FunctionPrefixUse Case
log_custom($msg)[CUSTOM]General custom logging
log_audit($msg)[AUDIT]User action tracking
log_api($msg)[API]API requests/responses
log_query($msg)[QUERY]Database queries
log_data($label, $data)Custom labelArrays/objects
log_exception($e)Class nameFull exception details

Examples

// Log user actions
log_audit('User 123 deleted item 456');

// Log API calls
log_api(['endpoint' => '/api/users', 'response_code' => 200]);

// Log arrays/objects nicely
log_data('Request payload', $request->getJSON());

// Log exceptions with full trace
try {
    // risky operation
} catch (Exception $e) {
    log_exception($e);
}

Output Example

INFO - 2025-01-10 12:30:00 --> [AUDIT] User 123 deleted item 456
INFO - 2025-01-10 12:30:01 --> [API] {"endpoint":"/api/users","response_code":200}
DEBUG - 2025-01-10 12:30:02 --> [QUERY] SELECT * FROM users WHERE id = 1
ERROR - 2025-01-10 12:30:03 --> InvalidArgumentException: Email invalid in /app/Domain/User.php:45
ESC

Start typing to search the documentation