Global Helper Functions

Introduction

Slenix ships with a comprehensive set of global helper functions available anywhere in your application — controllers, views, route closures, and Luna templates. These functions cover the most common tasks in web development: generating URLs, managing sessions, flashing messages, redirecting users, working with arrays, encoding data, and more.

You do not need to import or instantiate anything. Just call the function.


Environment

env()

Retrieves a value from the environment (.env file, $_ENV, or $_SERVER). Automatically casts the strings "true", "false", and "null" to their native PHP types.

php
$debug = env('APP_DEBUG');         // true or false (cast from string)
$name  = env('APP_NAME', 'App');   // second argument is the default

config()

A convenience wrapper around env() that accepts dot-notation keys and converts them to uppercase environment variable names.

php
config('app.debug')   // reads env('APP_DEBUG')
config('db.host')     // reads env('DB_HOST')

app_env()

Returns true if the current APP_ENV matches any of the given environment names.

php
if (app_env('production')) {
    // only in production
}

if (app_env('local', 'testing')) {
    // in local or testing
}

is_debug()

Returns true when APP_DEBUG is enabled.

php
if (is_debug()) {
    dump($query);
}

Paths

These functions return absolute paths within your project. Each accepts an optional relative path that is appended to the base directory.

php
base_path();                    // /var/www/myapp
base_path('composer.json');     // /var/www/myapp/composer.json

app_path('Models/User.php');    // /var/www/myapp/app/Models/User.php
public_path('css/app.css');     // /var/www/myapp/public/css/app.css
storage_path('logs/app.log');   // /var/www/myapp/storage/logs/app.log
views_path('auth/login.luna');  // /var/www/myapp/views/auth/login.luna
FunctionBase constant
base_path()ROOT_PATH
app_path()APP_PATH
public_path()PUBLIC_PATH
storage_path()STORAGE_PATH
views_path()VIEWS_PATH

Views

view()

Renders a Luna template and sends the output directly to the browser.

php
view('home.index');

view('user.profile', [
    'user' => $user,
    'posts' => $posts,
]);

Redirects

redirect()

Returns a fluent RedirectResponse object. The redirect is only sent when a terminal method such as to(), back(), or route() is called.

php
// Redirect to an explicit URL
redirect('/dashboard');

// Redirect back to the previous page
redirect()->back();

// Redirect to a named route
redirect()->route('login');

// Redirect with a fallback if the referer is not available
redirect()->back('/home');

Chaining Flash Data

You can attach data to the session before redirecting by chaining methods onto the response object. The data is available on the next request.

php
redirect('/profile')
    ->with('success', 'Profile updated.')
    ->withInput()
    ->withErrors(['name' => 'The name field is required.']);
MethodDescription
with(key, value)Flashes a single key-value pair to the session
withMany(array)Flashes multiple key-value pairs at once
withErrors(array, bag?)Flashes validation errors, optionally grouped by bag name
withInput(array?)Flashes the current $_POST data (sensitive fields removed automatically)

Flash Messages

flash()

Returns a FlashMessage instance for writing and reading flash data between requests.

Writing flash messages:

php
flash()->success('Your changes have been saved.');
flash()->error('Something went wrong. Please try again.');
flash()->warning('Your session is about to expire.');
flash()->info('A new version is available.');

// Custom key
flash()->write('verification_sent', true);

Reading flash messages in the next request:

php
if (flash()->has('success')) {
    echo flash()->get('success');
}

// Shorthand — type aliases work with or without the _flash_ prefix
flash()->get('error');    // resolves _flash_error
flash()->get('warning');  // resolves _flash_warning

// Get everything at once (non-destructive)
$all = flash()->all();

In Luna templates the flash() helper is shared automatically:

html
@if ($flash->has('success'))
    <div class="alert alert-success">{{ $flash->get('success') }}</div>
@endif

Session

session()

Provides a flexible interface for reading and writing session values.

php
// Retrieve a value
$userId = session('user_id');

// Store a value
session('theme', 'dark');

// Store multiple values at once
session(['locale' => 'en', 'timezone' => 'UTC']);

// Retrieve the fluent SessionManager instance
session()->put('cart', $items);
session()->forget('cart');

The SessionManager object returned by session() exposes the following methods:

MethodDescription
set(key, value)Stores a value in the session
`put(key\array, value?)`Stores one or multiple values
get(key, default?)Retrieves a value
has(key)Returns true if the key exists
missing(key)Returns true if the key does not exist
pull(key, default?)Retrieves and removes a value in one call
`forget(key\array)`Removes one or multiple keys
flush()Clears all session data without destroying the session
invalidate()Destroys the session completely
regenerate(deleteOld?)Regenerates the session ID (call after login/logout)
flash(key, value)Writes a flash value
getFlash(key, default?)Reads and removes a flash value
hasFlash(key)Checks whether a flash value exists
flashInput(array)Flashes form input for repopulation
increment(key, amount?)Increments a numeric value
decrement(key, amount?)Decrements a numeric value
push(key, value)Appends a value to an array stored in the session
id()Returns the current session ID
all()Returns the entire session as an array

Forms — Old Input & Validation Errors

old()

Returns the previously submitted value of a form field. This is populated by redirect()->withInput() or session()->flashInput().

php
old('email');           // returns the old value or empty string
old('name', 'Guest');   // returns 'Guest' if no old value exists

In Luna templates:

html
<input type="email" name="email" value="@old('email')">

errors()

Returns validation errors stored by redirect()->withErrors().

php
// All errors across all bags
errors();

// The first error message for a specific field
errors('email');         // returns string|null

// All error messages for a specific field
errors('email', true);   // returns array

has_error()

Returns true if the given field has at least one validation error.

php
has_error('email');

In Luna templates you can use these to conditionally apply CSS classes or display inline error messages:

html
<input
    type="text"
    name="name"
    class="{{ has_error('name') ? 'is-invalid' : '' }}"
    value="@old('name')"
>
@if (has_error('name'))
    <span class="error">{{ errors('name') }}</span>
@endif

URLs & Routes

url()

Generates an absolute URL using APP_BASE_URL as the base. Accepts an optional query-string array.

php
url('/about');                         // https://example.com/about
url('/search', ['q' => 'slenix']);     // https://example.com/search?q=slenix

asset()

An alias for url(). Use it for static files served from your public directory.

php
asset('css/app.css');     // https://example.com/css/app.css
asset('js/main.js');

route()

Generates a URL for a named route, optionally substituting route parameters.

php
route('home');
route('user.show', ['id' => 42]);     // https://example.com/users/42

current_url()

Returns the full URL of the current request, including query string.

php
current_url();    // https://example.com/dashboard?tab=settings

request_path()

Returns only the path of the current request, without the query string.

php
request_path();   // /dashboard

is_active()

Checks whether the current request path matches a pattern. Useful for highlighting active navigation items.

php
is_active('/home');          // exact match
is_active('/blog/*');        // wildcard — matches /blog/any-post

// Returns the second argument on match, third on no match
is_active('/dashboard', 'active', '');

In Luna templates:

html
<a href="/dashboard" class="{{ is_active('/dashboard', 'active') }}">Dashboard</a>

HTTP Responses

response()

Creates a Response object. Can be used as a factory for building responses.

php
return response('Not Found', 404);
return response(json_encode($data), 200);

abort()

Immediately terminates the request with the given HTTP status code. Automatically renders a JSON response when the client sends an Accept: application/json header, and an HTML error page otherwise.

php
abort(404);
abort(403, 'You do not have permission to access this resource.');

abort_if()

Calls abort() only when the given condition is true.

php
abort_if($user->isBanned(), 403);
abort_if(!$post->exists, 404, 'Post not found.');

abort_unless()

Calls abort() only when the given condition is false.

php
abort_unless($user->isAdmin(), 403);
abort_unless($token->isValid(), 401, 'Invalid token.');

Security

csrf_token()

Returns the current session's CSRF token as a raw string, generating one automatically if it does not yet exist.

php
$token = csrf_token();

csrf_field()

Returns a complete <input type="hidden"> element containing the CSRF token. Equivalent to the @csrf Luna directive.

php
echo csrf_field();
// <input type="hidden" name="_csrf_token" value="...">

method_field()

Returns a hidden input that signals the intended HTTP method. Used in HTML forms that must simulate PUT, PATCH, or DELETE.

php
echo method_field('PUT');
// <input type="hidden" name="_method" value="PUT">

In Luna templates:

html
<form method="POST" action="{{ route('post.update', ['id' => $post->id]) }}">
    @csrf
    @method('PUT')
    ...
</form>

encrypt() / decrypt()

Encrypt and decrypt strings using AES-256-GCM with your application's APP_KEY.

php
$cipher = encrypt('sensitive value');
$plain  = decrypt($cipher);          // 'sensitive value'

Note: decrypt() returns false if the ciphertext is invalid or has been tampered with.

hash_make() / hash_check()

Hashes a password using bcrypt with a cost of 12, and verifies a password against its stored hash.

php
$hash = hash_make('secret-password');

if (hash_check('secret-password', $hash)) {
    // password is correct
}

Strings

sanitize()

Trims whitespace and escapes HTML special characters.

php
sanitize('  <script>alert(1)</script>  ');
// '&lt;script&gt;alert(1)&lt;/script&gt;'

validate_name()

Returns true if the string contains only Unicode letters and spaces (supports accented characters).

php
validate_name('Cláudio Silva');   // true
validate_name('cl4udio!');        // false

camel_case() / snake_case() / pascal_case() / kebab_case()

Convert strings between common naming conventions.

php
camel_case('foo_bar_baz');    // 'fooBarBaz'
snake_case('FooBarBaz');      // 'foo_bar_baz'
pascal_case('foo-bar-baz');   // 'FooBarBaz'
kebab_case('FooBarBaz');      // 'foo-bar-baz'

str_default()

Returns the string as-is, or the default if the string is empty or null.

php
str_default('', 'Anonymous');      // 'Anonymous'
str_default('Claudio', 'Anonymous'); // 'Claudio'

limit()

Truncates a string to the given character length, appending a suffix.

php
limit('Hello, World!', 7);          // 'Hello, ...'
limit('Hello, World!', 7, ' →');    // 'Hello,  →'

str_slug()

Converts a string into a URL-friendly slug.

php
str_slug('Olá, Mundo!');          // 'ola-mundo'
str_slug('Hello World', '_');     // 'hello_world'

str_contains_any()

Returns true if the string contains at least one of the values in the given array.

php
str_contains_any('Hello World', ['World', 'Earth']);   // true
str_contains_any('Hello World', ['Mars', 'Venus']);    // false

mask()

Replaces part of a string with a repeating character.

php
mask('joao@email.com', '*', 2, 8);   // 'jo********mail.com'
mask('4111111111111111', '*', 0, 12); // '************1111'

Arrays

is_empty()

Returns true if the value is null, an empty string, or an empty array.

php
is_empty(null);   // true
is_empty('');     // true
is_empty([]);     // true
is_empty(0);      // false

array_get()

Retrieves a value from a nested array using dot-notation. Returns the default if the key does not exist.

php
$data = ['user' => ['address' => ['city' => 'Luanda']]];

array_get($data, 'user.address.city');        // 'Luanda'
array_get($data, 'user.address.zip', 'N/A'); // 'N/A'

array_set()

Sets a value in a nested array using dot-notation, creating intermediate keys as needed.

php
$data = [];
array_set($data, 'user.address.city', 'Luanda');
// $data = ['user' => ['address' => ['city' => 'Luanda']]]

array_only()

Returns a new array containing only the specified keys.

php
array_only(['name' => 'Ana', 'email' => 'ana@x.com', 'password' => '...'], ['name', 'email']);
// ['name' => 'Ana', 'email' => 'ana@x.com']

array_except()

Returns a new array with the specified keys removed.

php
array_except(['name' => 'Ana', 'password' => '...'], ['password']);
// ['name' => 'Ana']

array_flatten()

Collapses a multi-dimensional array into a single flat array.

php
array_flatten([[1, 2], [3, [4, 5]]]);
// [1, 2, 3, 4, 5]

array_wrap()

Ensures a value is always an array. Wraps non-array values, returns empty array for null.

php
array_wrap('hello');   // ['hello']
array_wrap(['hello']); // ['hello']
array_wrap(null);      // []

collect()

Wraps an array in a fluent Collection object with chainable methods.

php
$users = collect($userArray)
    ->filter(fn($u) => $u['active'])
    ->sortBy('name')
    ->pluck('email')
    ->take(10)
    ->all();

Available Collection methods:

MethodDescription
all()Returns the underlying array
count()Number of items
isEmpty() / isNotEmpty()Emptiness checks
first(default?) / last(default?)Access first or last item
map(callback)Transforms each item
filter(callback?)Filters items, re-indexes result
each(callback)Iterates without transforming
pluck(key)Extracts a column by key
where(key, value)Filters by key-value equality
sortBy(key, direction?)Sorts by a key (asc or desc)
unique(key?)Removes duplicate values or rows
chunk(size)Splits into chunks of the given size
take(limit)Returns the first N items
skip(count)Skips the first N items
contains(value)Checks for strict membership
sum(key?)Sums values or a column
avg(key?)Averages values or a column
push(item)Appends an item
merge(array)Merges another array
keys() / values()Returns keys or re-indexed values
reverse()Reverses item order
shuffle()Randomly shuffles items
paginate(perPage, page?)Slices for pagination and returns metadata
toArray()Alias for all()
toJson()JSON-encodes the collection

JSON

to_json()

Encodes a value to a pretty-printed, UTF-8-safe JSON string.

php
to_json(['name' => 'Cláudio', 'active' => true]);

from_json()

Decodes a JSON string, returning an associative array by default.

php
$data = from_json('{"name":"Cláudio"}');
$data['name']; // 'Cláudio'

// Return as stdClass
from_json('{"name":"Cláudio"}', false);

Dates

now()

Returns the current date and time as a DateTimeImmutable instance.

php
$date = now();
echo $date->format('Y-m-d H:i:s');

format_date()

Parses a date string and formats it. Returns null if parsing fails.

php
format_date('2025-01-15', 'd/m/Y');         // '15/01/2025'
format_date('2025-01-15 14:30:00');         // '15/01/2025 14:30:00'
format_date('not-a-date');                  // null

human_date()

Converts a date into a human-readable relative string in Portuguese.

php
human_date('2025-01-14 10:00:00');   // 'há 3 dias'
human_date(now()->modify('-2 hours')); // 'há 2 horas'

Debug

dd()

Dumps one or more values with styled output and immediately terminates execution.

php
dd($user, $request, $config);

dump()

Same as dd() but does not stop execution.

php
dump($user);
// execution continues

benchmark()

Returns the number of milliseconds elapsed since the application started (SLENIX_START).

php
echo benchmark() . ' ms';

Luna Template Sharing

All helpers are automatically shared with Luna templates. The following variables are injected into every template without any extra configuration:

VariableTypeDescription
$routeClosureCalls route(name, params)
$csrf_tokenClosureReturns the CSRF token string
$csrf_fieldClosureReturns the hidden CSRF input
$oldClosureReturns old form input
$errorsClosureReturns validation errors
$has_errorClosureChecks if a field has an error
$flashFlashMessageFlash message instance
$is_activeClosureChecks active route pattern
$assetClosureGenerates an asset URL
$urlClosureGenerates a full URL
$SessionarrayArray of session method closures

The $Session array exposes: has, get, set, flash, getFlash, hasFlash, remove, all, and destroy.