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
The configuration key using dot notation (e.g., ‘app.name’, ‘db.connections’)
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
The environment variable name
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
The name of the view template to render
Associative array of data to pass to the view
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
The data to return. If null, returns the Response instance
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
The response data to display
HTTP status code (default: 403)
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
The component name to render
Data to pass to the component
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
Request options or HTTP method. If empty, returns the Request instance
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
The URL or route to redirect to
Query parameters or route parameters
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
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 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
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.
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
Security policy categories to apply from config(‘security’)
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 & Cookie Helpers
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();
cookie()
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 value. If null with a name, retrieves the cookie value
Cookie expiration time in seconds
Path on server where cookie is available (default: ”/”)
Domain that the cookie is available to
Only transmit over HTTPS (default: false)
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
The FILESarrayelement(e.g.,_FILES[‘document’])
Target directory. If null, uses config default
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
The directory path to scan
Optional array of specific filenames to filter by
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
The directory path containing PHP files
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
Path and filename for the log file. If empty, uses error.log
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
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
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
Example:
echo pluralize('user'); // "users"
echo pluralize('child'); // "children"
singularize()
Converts a word to its singular form.
function singularize(string $word): array
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
The fully qualified class name
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
Maximum length of the resulting string (default: 30)
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
Maximum length of the resulting string (default: 30)
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
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
Associative array where keys use dot notation for nested structure
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
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
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
}