Skip to main content

Overview

Aeros provides a comprehensive set of global helper functions that simplify common tasks like accessing services, managing configurations, handling requests, and manipulating strings. All helper functions are available globally without requiring any imports.

Core Framework Helpers

app()

Bootstraps and returns the application service container instance.
function app(): \Aeros\Src\Classes\ServiceContainer
Returns: The singleton ServiceContainer instance Throws: \Exception if bootstrapping fails Example:
$container = app();
$basedir = app()->basedir;

config()

Returns values or objects from configuration files.
function config(string $from, mixed $default = null): mixed
from
string
required
The configuration key using dot notation (e.g., ‘app.name’, ‘db.connections’)
default
mixed
Default value to return if the configuration key is not found
Example:
$appName = config('app.name');
$dbHost = config('db.connections.mysql.host', 'localhost');

env()

Gets an environment variable if it exists, otherwise returns the default value.
function env(string $key, $default = null): mixed
key
string
required
The environment variable name
default
mixed
Default value to return if the variable is not set
Example:
$appEnv = env('APP_ENV', 'production');
$debug = env('APP_DEBUG', false);

View & Response Helpers

view()

Renders and returns a view template with optional data.
function view(string $view, array $values = [], string $subfolder = ''): mixed
view
string
required
The name of the view template to render
values
array
Associative array of data to pass to the view
subfolder
string
Optional subfolder within the views directory
Example:
return view('home', ['title' => 'Welcome']);
return view('admin/dashboard', ['user' => $user], 'admin');

response()

Formats and returns content as JSON, XML, HTML, or other content types.
function response($data = null, int $code = null, string $type = \Aeros\Src\Classes\Response::HTML): mixed
data
mixed
The data to return. If null, returns the Response instance
code
int
HTTP status code
type
string
Content type (Response::HTML, Response::JSON, Response::XML)
Example:
return response(['status' => 'success'], 200, Response::JSON);
return response()->json(['data' => $items]);

abort()

Terminates the script and returns a response with the specified status code.
function abort($data = null, int $code = 403, string $type = \Aeros\Src\Classes\Response::HTML): void
data
mixed
The response data to display
code
int
HTTP status code (default: 403)
type
string
Content type for the response
Example:
abort('Unauthorized', 401);
abort(['error' => 'Not found'], 404, Response::JSON);

component()

Renders a component and returns HTML content.
function component(string $component, array $data = [], bool $dump = true): mixed
component
string
required
The component name to render
data
array
Data to pass to the component
dump
bool
If true, outputs the component. If false, returns the component body
Example:
component('navbar', ['active' => 'home']);
$html = component('card', ['title' => 'Info'], false);

Request & Redirect Helpers

request()

Handles HTTP requests with cURL or retrieves request data from specific HTTP methods.
function request(mixed $opts = '', array $keys = []): mixed
opts
mixed
Request options or HTTP method. If empty, returns the Request instance
keys
array
Specific keys to extract from the request
Example:
$email = request()->get('email');
$data = request('POST', ['name', 'email']);

redirect()

Performs a redirect to a specified URL with optional arguments.
function redirect(string $redirect, array $arguments = [], string $request_method = 'GET'): void
redirect
string
required
The URL or route to redirect to
arguments
array
Query parameters or route parameters
request_method
string
The HTTP method for the redirect (default: ‘GET’)
Example:
redirect('/dashboard');
redirect('/user/profile', ['id' => 123]);

validate()

Validates request data with filter rules.
function validate(array $rules): array
rules
array
required
Validation rules to apply to the request data
Returns: Array of validated data Example:
$data = validate([
    'email' => 'required|email',
    'password' => 'required|min:8'
]);

Database & Cache Helpers

db()

Returns a database connection instance.
function db(string $connection = null): \Aeros\Src\Classes\Db
connection
string
Connection name from config (e.g., ‘sqlite-server-01’). If null, uses default connection
Example:
$users = db()->table('users')->get();
$posts = db('mysql-secondary')->table('posts')->where('status', 'published')->get();

cache()

Returns a cache instance for the specified connection.
function cache($connection = null): mixed
connection
string
Cache connection name. If null, uses default connection
Example:
cache()->set('user:1', $userData, 3600);
$user = cache()->get('user:1');
cache('redis')->flush();

Security Helpers

csrf()

Embeds a CSRF token into a hidden input field.
function csrf(): void
Example:
<form method="POST">
    <?php csrf(); ?>
    <input type="text" name="email">
    <button type="submit">Submit</button>
</form>

sanitizeWith()

Sanitizes a value using specified security policies.
function sanitizeWith($vector, array $categories, string $replacement = ''): mixed
vector
mixed
required
The value to sanitize
categories
array
required
Security policy categories to apply from config(‘security’)
replacement
string
String to replace sanitized content with
Example:
$clean = sanitizeWith($userInput, ['xss', 'sql']);

encryptor()

Returns the global encryptor instance.
function encryptor(): \Aeros\Src\Classes\Encryptor
Example:
$encrypted = encryptor()->encrypt('sensitive data');
$decrypted = encryptor()->decrypt($encrypted);

session()

Returns the global session object.
function session(): \Aeros\Src\Classes\Session
Example:
// Set session data using magic methods
session()->user_id = 123;
session()->username = 'john_doe';

// Get session data
$userId = session()->user_id;

// Check if session variable exists
if (isset(session()->user_id)) {
    // Variable exists
}

// Remove session variable
unset(session()->user_id);

// Renovate (destroy and restart) session
session()->renovate();

// Close session
session()->close();

Manages cookies - get, set, or retrieve the CookieJar instance.
function cookie(
    string $cookie_name = null,
    mixed $cookie_value = null,
    int $cookie_expiration = 0,
    string $path = "/",
    string $cookie_domain = '',
    bool $secure = false,
    bool $httponly = true
): mixed
The cookie name
The cookie value. If null with a name, retrieves the cookie value
Cookie expiration time in seconds
path
string
Path on server where cookie is available (default: ”/”)
Domain that the cookie is available to
secure
bool
Only transmit over HTTPS (default: false)
httponly
bool
Only accessible via HTTP protocol (default: true)
Example:
// Get cookie value
$token = cookie('auth_token');

// Set cookie
cookie('auth_token', 'abc123', 3600);

// Access CookieJar instance
cookie()->delete('old_token');

File & Storage Helpers

store()

Uploads and stores file(s), returning file information.
function store(array $uploadedFiles, ?string $directory = null, array $options = []): array
uploadedFiles
array
required
The FILESarrayelement(e.g.,_FILES array element (e.g., _FILES[‘document’])
directory
string
Target directory. If null, uses config default
options
array
Override options like [‘name’ => ‘custom.jpg’, ‘overwrite’ => false]
Returns: Array of file information including path, name, size, mime, etc. Example:
$files = store($_FILES['documents'], '/uploads/docs');
foreach ($files as $file) {
    echo $file['path'] . ' - ' . $file['size'];
}

scan()

Scans a directory for files with specific extensions.
function scan(string $path, array $filenames = [], $extensions = ['php']): array
path
string
required
The directory path to scan
filenames
array
Optional array of specific filenames to filter by
extensions
mixed
Array of file extensions to filter by (default: [‘php’])
Returns: Array of matching filenames Throws: \Exception if path is empty or directory doesn’t exist Example:
$phpFiles = scan('/app/Controllers');
$configFiles = scan('/app/config', [], ['json', 'yaml']);

load()

Loads PHP files from a specified directory.
function load(string $path, array $filenames = []): bool
path
string
required
The directory path containing PHP files
filenames
array
Optional array of specific filenames to load
Returns: True if files are loaded successfully Throws: \Exception if no files are found Example:
load('/app/Helpers');
load('/app/Config', ['database', 'cache']);

Background Tasks & Scheduling

queue()

Returns the queue instance for background job processing.
function queue(): \Aeros\Src\Classes\Queue
Example:
queue()->push(new SendEmailJob($user));
queue()->process();

worker()

Returns the main application worker instance.
function worker(): \Aeros\Src\Classes\Worker
Example:
worker()->start();
worker()->process($job);

cron()

Returns the cron scheduler instance.
function cron(): \Aeros\Src\Classes\Cron
Example:
cron()->schedule('daily-backup', '0 2 * * *', function() {
    // Backup logic
});

Rate Limiting & CORS

rateLimiter()

Returns the rate limiter instance.
function rateLimiter(): \Aeros\Src\Classes\RateLimiter
Throws: \Exception if rate limiter is not configured Example:
rateLimiter()->attempt('api:' . $userId, 60, 100);

cors()

Returns the CORS whitelist service provider.
function cors(): \App\Providers\CorsWhitelistServiceProvider
Throws: \Exception if CORS is not configured Example:
cors()->allow('https://example.com');

Logging & Debugging

logger()

Appends a message to a log file.
function logger(mixed $message, string $logFile = '', bool $createFile = false): bool
message
mixed
required
The message to log
logFile
string
Path and filename for the log file. If empty, uses error.log
createFile
bool
Whether to create the log file if it doesn’t exist
Example:
logger('User login attempt', 'auth.log');
logger(['error' => 'Connection failed'], 'errors.log', true);

dd()

Dumps variables and terminates script execution (dump and die).
function dd(...$args): void
args
mixed
required
Variables to dump
Example:
dd($user, $request, $config);

String Manipulation Helpers

str_find()

Searches for strings within another string based on a list.
function str_find(string $haystack, array $needles): bool
haystack
string
required
The string to search in
needles
array
required
Array of strings to search for
Returns: True if any needle is found at the start of the haystack Example:
if (str_find($url, ['http://', 'https://'])) {
    // URL starts with http:// or https://
}

pluralize()

Converts a word to its plural form.
function pluralize(string $word): string
word
string
required
The word to pluralize
Example:
echo pluralize('user');  // "users"
echo pluralize('child'); // "children"

singularize()

Converts a word to its singular form.
function singularize(string $word): array
word
string
required
The word to singularize
Returns: Array of possible singular forms Example:
$singular = singularize('users');  // ["user"]

class_basename()

Extracts the class name from a fully qualified class name.
function class_basename(string $string, string $separator = '\\'): string
string
string
required
The fully qualified class name
separator
string
The namespace separator (default: ’\’)
Example:
echo class_basename('Aeros\Classes\User'); // "User"

truncate()

Truncates a string to a specified length with a substitute.
function truncate(string $string, int $length = 30, string $substitute = '...'): string
string
string
required
The string to truncate
length
int
Maximum length of the resulting string (default: 30)
substitute
string
The string to append when truncated (default: ’…’)
Example:
echo truncate('This is a very long sentence', 15); // "This is a ve..."

truncateAtWord()

Truncates a string at the last complete word within the specified length.
function truncateAtWord(string $string, int $length = 30, string $substitute = '...'): string
string
string
required
The string to truncate
length
int
Maximum length of the resulting string (default: 30)
substitute
string
The string to append when truncated (default: ’…’)
Example:
echo truncateAtWord('This is a very long sentence', 15); // "This is a..."

Configuration Management

updateEnvVariable()

Updates environment variables in the .env file.
function updateEnvVariable(array $newEnvValues): bool|int
newEnvValues
array
required
Associative array of environment variable names and values
Returns: Number of bytes written on success, false on failure Example:
updateEnvVariable(['APP_KEY' => 'new-app-key-123']);

updateJsonNode()

Updates values of nested nodes in a JSON file.
function updateJsonNode(array $keyValues, string $jsonFile): bool|int
keyValues
array
required
Associative array where keys use dot notation for nested structure
jsonFile
string
required
Path to the JSON file to update
Returns: True on success, false if key not found, or bytes written Example:
updateJsonNode(
    ['environments.staging.name' => 'newdb'],
    app()->basedir . '/../phinx.json'
);

Environment Helpers

isMode()

Checks if the current Server API mode matches the specified mode.
function isMode(string $mode): bool
mode
string
required
The SAPI mode to check: ‘cli’, ‘cli-server’, ‘cgi-fcgi’, ‘fpm-fcgi’, ‘litespeed’, ‘embed’, ‘phpdbg’
Example:
if (isMode('cli')) {
    echo "Running in command line mode";
}

isEnv()

Determines if the environment matches the requested label.
function isEnv(string|array $env): bool
env
string|array
required
Environment name(s) to check against APP_ENV
Example:
if (isEnv('production')) {
    // Production-specific code
}

if (isEnv(['staging', 'production'])) {
    // Staging or production code
}

isInternal()

Validates if the current user is internal (based on IP or environment).
function isInternal(): bool
Returns: True if the user is internal, false otherwise Example:
if (isInternal()) {
    // Show admin features
}

Build docs developers (and LLMs) love