Skip to content

Helper Function

Precious Lyson edited this page Nov 13, 2026 · 4 revisions

The Machinjiri Framework provides a comprehensive set of global helper functions that simplify common development tasks. These helpers are designed to reduce boilerplate code and make your application more readable and maintainable.

What are Helper Functions?

Helper functions are globally accessible PHP functions that provide convenient shortcuts for common operations. They're automatically available throughout your application without requiring imports or namespace declarations.

Benefits

  • Reduced Boilerplate: Write less code to accomplish common tasks
  • Consistency: Standardized approach to common operations
  • Readability: Self-documenting function names
  • Flexibility: Most helpers support optional parameters for customization

Getting Started

Prerequisites

  • Machinjiri Framework installed and configured

Basic Usage

Helper functions are automatically loaded by the framework. You can use them anywhere in your application:

// Get current date/time
$now = now();

// Get configuration value
$appName = config('app.name');

// Generate a URL
$url = route_url('user.profile', ['id' => 1]);

// Debug variables
dd($user, $posts, $comments);

Application & Container Helpers

app()

Get the application container instance or resolve a service.

Signature:

function app(?string $abstract = null): Container|mixed

Parameters:

  • $abstract (string|null): Optional service name to resolve

Returns:

  • Container: The container instance when no abstract is provided
  • mixed: The resolved service when an abstract is provided

Examples:

// Get the container instance
$container = app();

// Resolve a service
$logger = app(Logger::class);

// Check if a service is bound
if (app()->bound(Mailer::class)) {
    $mailer = app(Mailer::class);
}

resolve()

Resolve a service from the container with optional parameters.

Signature:

function resolve(string $abstract, array $parameters = []): mixed

Parameters:

  • $abstract (string): Service name to resolve
  • $parameters (array): Parameters to pass to the constructor

Returns:

  • mixed: The resolved service instance

Throws:

  • MachinjiriException: When container is not initialized (code: 30104)
  • MachinjiriException: When container lacks resolve method (code: 30105)

Examples:

// Basic resolution
$logger = resolve(Logger::class);

// With parameters
$mailer = resolve(Mailer::class, [
    'host' => 'smtp.example.com',
    'port' => 587
]);

singleton()

Register a singleton service in the container. Singletons are instantiated once and reused.

Signature:

function singleton(string $abstract, $concrete = null): void

Parameters:

  • $abstract (string): The service identifier
  • $concrete (mixed): The implementation (class name, closure, or instance)

Examples:

// Register a singleton with a class name
singleton(Logger::class, FileLogger::class);

// Register with a closure
singleton(CacheManager::class, function ($container) {
    return new CacheManager($container->make(Config::class));
});

// Register the abstract itself as singleton
singleton(Database::class);

bind()

Register a binding in the container.

Signature:

function bind(string $abstract, $concrete = null, bool $shared = false): void

Parameters:

  • $abstract (string): The service identifier
  • $concrete (mixed): The implementation
  • $shared (bool): Whether to share the instance (singleton behavior)

Examples:

// Bind an interface to an implementation
bind(MailerInterface::class, SmtpMailer::class);

// Bind with a closure
bind(PaymentGateway::class, function ($container) {
    return new StripeGateway(
        $container->make(Config::class)->get('stripe.key')
    );
});

// Bind as shared (singleton)
bind(Cache::class, RedisCache::class, true);

alias()

Register an alias for a service.

Signature:

function alias(string $abstract, string $alias): void

Parameters:

  • $abstract (string): The original service identifier
  • $alias (string): The alias name

Examples:

// Register a service
singleton(FileLogger::class);

// Create an alias
alias(FileLogger::class, 'logger');
alias(FileLogger::class, LoggerInterface::class);

// Now both work
$logger1 = app(FileLogger::class);
$logger2 = app('logger');
$logger3 = app(LoggerInterface::class);

service()

Get a service provider instance.

Signature:

function service(string $providerClass): ?ServiceProvider

Parameters:

  • $providerClass (string): The service provider class name

Returns:

  • ServiceProvider|null: The provider instance or null if container unavailable

Examples:

// Get a service provider
$provider = service(AppServiceProvider::class);

// Use the provider
if ($provider !== null) {
    $provider->register();
}

service_provider()

Check if a service provider is registered.

Signature:

function service_provider(string $providerClass): bool

Parameters:

  • $providerClass (string): The service provider class name

Returns:

  • bool: True if registered, false otherwise

Examples:

if (service_provider(AppServiceProvider::class)) {
    echo "AppServiceProvider is registered!";
}

boot_service_provider()

Boot a specific service provider.

Signature:

function boot_service_provider(string $providerClass): bool

Parameters:

  • $providerClass (string): The service provider class name

Returns:

  • bool: True if booted successfully, false otherwise

Examples:

$booted = boot_service_provider(AppServiceProvider::class);

if ($booted) {
    echo "Provider booted successfully!";
}

Configuration Helpers

config()

Get or set configuration values using dot notation.

Signature:

function config($key = null, $default = null): mixed

Parameters:

  • $key (string|array|null): Configuration key (dot notation) or array to set multiple values
  • $default (mixed): Default value if key not found

Returns:

  • mixed: The configuration value, all configurations, or default

Examples:

// Get all configurations
$allConfig = config();

// Get a specific value
$appName = config('app.name');

// Get with default
$timezone = config('app.timezone', 'UTC');

// Get nested value
$dbHost = config('database.connections.mysql.host');

// Set configuration values
config([
    'app.debug' => true,
    'app.env' => 'development'
]);

// Set a single value
config(['app.name' => 'My Application']);

app_configurations()

Get application configurations from the container.

Signature:

function app_configurations(string $key = ''): array

Parameters:

  • $key (string): Optional key to retrieve specific configuration section

Returns:

  • array: Configuration array

Examples:

// Get all configurations
$configs = app_configurations();

// Get specific section
$dbConfig = app_configurations('database');

config_path()

Get the full path to a configuration file.

Signature:

function config_path(string $filename = ''): string

Parameters:

  • $filename (string): Configuration filename (with or without .php extension)

Returns:

  • string: Full path to the configuration file

Examples:

// Get config directory
$configDir = config_path();

// Get path to app.php config file
$appConfig = config_path('app'); // Returns: /path/to/project/config/app.php

// With extension
$dbConfig = config_path('database.php');

Path Helpers

base_path()

Get the base path of the application.

Signature:

function base_path(string $path = ''): string

Parameters:

  • $path (string): Subdirectory or file path within base

Returns:

  • string: Full path

Examples:

// Get base path
$base = base_path(); // /var/www/myapp

// Get path to a file
$file = base_path('composer.json'); // /var/www/myapp/composer.json

app_path()

Get the path to the application directory.

Signature:

function app_path(string $path = ''): string

Examples:

// Get app directory
$appDir = app_path(); // /var/www/myapp/app

// Get path to a controller
$controller = app_path('Controllers/UserController.php');

public_path()

Get the path to the public directory.

Signature:

function public_path(string $path = ''): string

Examples:

// Get public directory
$public = public_path(); // /var/www/myapp/public

// Get path to CSS file
$css = public_path('css/app.css');

resource_path()

Get the path to the resources directory.

Signature:

function resource_path(string $path = ''): string

Examples:

// Get resources directory
$resources = resource_path(); // /var/www/myapp/resources

// Get path to view
$view = resource_path('views/welcome.php');

storage_path()

Get the path to the storage directory.

Signature:

function storage_path(string $path = ''): string

Examples:

// Get storage directory
$storage = storage_path(); // /var/www/myapp/storage

// Get path to logs
$logs = storage_path('logs/app.log');

// Get path to cache
$cache = storage_path('cache');

database_path()

Get the path to the database directory.

Signature:

function database_path(string $path = ''): string

Examples:

// Get database directory
$dbDir = database_path(); // /var/www/myapp/database

// Get path to migrations
$migrations = database_path('migrations');

// Get path to SQLite file
$sqlite = database_path('database.sqlite');

Environment Helpers

env()

Get environment variable values.

Signature:

function env(string $key, $default = null): mixed

Parameters:

  • $key (string): Environment variable name
  • $default (mixed): Default value if not found

Returns:

  • mixed: The environment variable value or default

Examples:

// Get environment variable
$dbHost = env('DB_HOST');

// With default value
$dbPort = env('DB_PORT', 3306);

// Boolean-like values
$debug = env('APP_DEBUG', false);

// Check environment
if (env('APP_ENV') === 'production') {
    // Production-specific code
}

Environment File Example (.env):

APP_NAME="My Application"
APP_ENV=local
APP_DEBUG=true
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=secret

Caching Helpers

cache_manager()

Get the CacheManager instance.

Signature:

function cache_manager(): CacheManager

Returns:

  • CacheManager: The cache manager instance

Examples:

// Get cache manager
$cache = cache_manager();

// Store a value
cache_manager()->set('user:1', $userData, 3600);

// Retrieve a value
$user = cache_manager()->get('user:1');

// Check if key exists
if (cache_manager()->has('user:1')) {
    // Cache hit
}

// Remove from cache
cache_manager()->delete('user:1');

// Clear all cache
cache_manager()->flush();

Common Cache Operations:

$cache = cache_manager();

// Store with expiration (seconds)
$cache->set('key', 'value', 3600);

// Store forever
$cache->forever('key', 'value');

// Get with default
$value = $cache->get('key', 'default');

// Get or set (cache-aside pattern)
$users = $cache->remember('users.all', 3600, function () {
    return query_builder('users')->get();
});

// Increment
$cache->increment('page.views');

// Decrement
$cache->decrement('credits');

Database Helpers

query_builder()

Create a new QueryBuilder instance.

Signature:

function query_builder(string $table = ''): QueryBuilder

Parameters:

  • $table (string): The table name

Returns:

  • QueryBuilder: The query builder instance

Examples:

// Simple select
$users = query_builder('users')->get();

// Select with conditions
$activeUsers = query_builder('users')
    ->where('status', 'active')
    ->where('age', '>=', 18)
    ->get();

// Select specific columns
$names = query_builder('users')
    ->select(['id', 'name', 'email'])
    ->get();

// Insert
$id = query_builder('users')->insert([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'created_at' => now()
]);

// Update
query_builder('users')
    ->where('id', 1)
    ->update(['status' => 'inactive']);

// Delete
query_builder('users')
    ->where('id', 1)
    ->delete();

// Join
$posts = query_builder('posts')
    ->join('users', 'posts.user_id', '=', 'users.id')
    ->select(['posts.*', 'users.name as author_name'])
    ->get();

// Order and limit
$recentPosts = query_builder('posts')
    ->orderBy('created_at', 'DESC')
    ->limit(10)
    ->get();

// Count
$total = query_builder('users')->count();

// First result
$user = query_builder('users')->where('id', 1)->first();

cached_query_builder()

Create a new CachedQueryBuilder instance for automatic query result caching.

Signature:

function cached_query_builder(string $table = ''): CachedQueryBuilder

Parameters:

  • $table (string): The table name

Returns:

  • CachedQueryBuilder: The cached query builder instance

Examples:

// Queries through cached_query_builder are automatically cached
$users = cached_query_builder('users')->get();

// With cache TTL (in seconds)
$users = cached_query_builder('users')
    ->cacheFor(3600)
    ->where('status', 'active')
    ->get();

// Complex query with caching
$popularPosts = cached_query_builder('posts')
    ->cacheFor(1800)
    ->where('views', '>', 1000)
    ->orderBy('views', 'DESC')
    ->limit(10)
    ->get();

// Cached query with joins
$userPosts = cached_query_builder('posts')
    ->cacheFor(600)
    ->join('users', 'posts.user_id', '=', 'users.id')
    ->where('users.status', 'active')
    ->get();

Date & Time Helpers

datetime_handler()

Get a DateTimeHandler instance.

Signature:

function datetime_handler(?string $timezone = null): DateTimeHandler

Parameters:

  • $timezone (string|null): Timezone string (defaults to config or UTC)

Returns:

  • DateTimeHandler: The date/time handler instance

Examples:

// Get handler with default timezone
$dt = datetime_handler();

// Get handler with specific timezone
$dt = datetime_handler('America/New_York');

// Common operations
$dt = datetime_handler();
echo $dt->format('Y-m-d');                    // 2024-01-15
echo $dt->format('F j, Y g:i A');            // January 15, 2024 3:30 PM
echo $dt->addDays(7)->format('Y-m-d');       // 7 days from now
echo $dt->subHours(2)->format('H:i');        // 2 hours ago

now()

Get current date and time.

Signature:

function now(string $format = ''): string

Parameters:

  • $format (string): Optional format string (defaults to 'Y-m-d h:i:s')

Returns:

  • string: Formatted current date/time

Examples:

// Default format
$timestamp = now(); // 2024-01-15 03:30:45

// Custom formats
$date = now('Y-m-d');              // 2024-01-15
$time = now('H:i:s');              // 03:30:45
$readable = now('F j, Y');         // January 15, 2024
$full = now('l, F j, Y g:i A');    // Monday, January 15, 2024 3:30 AM

// Use in database operations
query_builder('posts')->insert([
    'title' => 'New Post',
    'created_at' => now(),
    'updated_at' => now()
]);

Debugging Helpers

dump()

Dump variables for inspection and continue execution.

Signature:

function dump(...$args): void

Parameters:

  • ...$args: Variables to dump

Examples:

// Dump single variable
dump($user);

// Dump multiple variables
dump($user, $posts, $comments);

// Dump and continue
dump($request->all());
$response = processData($request); // Continues execution
dump($response);

dd()

Dump variables and terminate the script (die and dump).

Signature:

function dd(...$args): never

Parameters:

  • ...$args: Variables to dump

Examples:

// Dump and die
dd($user);

// Dump multiple variables
dd($request, $response, $errors);

// Common debugging pattern
if ($debug) {
    dd($query, $bindings, $results);
}

debugger()

Get the Debugger instance.

Signature:

function debugger(): Debugger

Returns:

  • Debugger: The debugger singleton instance

Examples:

// Get debugger instance
$debugger = debugger();

// Access debugger methods
debugger()->startTimer('operation');
// ... code to measure ...
debugger()->endTimer('operation');

debug()

Log a debug message.

Signature:

function debug($message, array $context = []): void

Parameters:

  • $message (mixed): The message to log
  • $context (array): Additional context data

Examples:

// Simple debug message
debug('User logged in');

// With context
debug('User action', [
    'user_id' => $user->id,
    'action' => 'login',
    'ip' => $_SERVER['REMOTE_ADDR']
]);

// Debug complex data
debug('Query results', [
    'query' => $sql,
    'bindings' => $bindings,
    'count' => count($results)
]);

measure()

Measure execution time of a callable.

Signature:

function measure(callable $callback, string $label = 'anonymous'): mixed

Parameters:

  • $callback (callable): The function to measure
  • $label (string): Label for the measurement

Returns:

  • mixed: The return value of the callback

Examples:

// Measure a function
$result = measure(function () {
    return processLargeDataset($data);
}, 'data_processing');

// Measure database query
$users = measure(function () {
    return query_builder('users')->get();
}, 'fetch_users');

// Measure with closure capturing variables
$userId = 123;
$user = measure(function () use ($userId) {
    return query_builder('users')->find($userId);
}, 'fetch_single_user');

Event Helpers

event()

Trigger an event or register an event listener.

Signature:

function event(string $event, $data = null): void|mixed

Parameters:

  • $event (string): Event name
  • $data (mixed): Event data or listener callback

Behavior:

  • With 1 argument: Triggers the event
  • With 2 arguments and callback: Registers a listener
  • With 2 arguments and non-callback: Triggers event with data

Examples:

// Register an event listener
event('user.registered', function ($user) {
    // Send welcome email
    $mailer = resolve(Mailer::class);
    $mailer->send($user->email, 'Welcome!', 'welcome-template');
});

// Trigger an event
event('user.registered', $user);

// Trigger event without data
event('app.maintenance');

// Register multiple listeners for the same event
event('order.placed', function ($order) {
    // Send confirmation email
});

event('order.placed', function ($order) {
    // Update inventory
});

event('order.placed', function ($order) {
    // Notify warehouse
});

// Trigger - all listeners will be called
event('order.placed', $order);

Common Event Patterns:

// Model events
event('model.created', $user);
event('model.updated', $user);
event('model.deleted', $user);

// Application events
event('app.starting');
event('app.started');
event('app.shutdown');

// Custom events with data
event('payment.completed', [
    'order_id' => $order->id,
    'amount' => $order->total,
    'gateway' => 'stripe'
]);

HTTP Client Helpers

http_client()

Create a new HttpClient instance.

Signature:

function http_client(string $baseUrl = '', ?Session $session = null, ?Cookie $cookie = null): HttpClient

Parameters:

  • $baseUrl (string): Base URL for requests
  • $session (Session|null): Session instance for cookies
  • $cookie (Cookie|null): Cookie instance

Returns:

  • HttpClient: The HTTP client instance

Examples:

// Basic client
$client = http_client();

// With base URL
$client = http_client('https://api.example.com');

// Make requests
$response = $client->get('/users');
$response = $client->post('/users', ['name' => 'John']);

http_get()

Execute a GET request.

Signature:

function http_get(string $url, array $queryParams = [], array $options = []): array

Parameters:

  • $url (string): Request URL
  • $queryParams (array): Query parameters
  • $options (array): Additional cURL options

Returns:

  • array: Response data

Examples:

// Simple GET request
$response = http_get('https://api.example.com/users');

// With query parameters
$response = http_get('https://api.example.com/users', [
    'page' => 1,
    'limit' => 20,
    'status' => 'active'
]);

// With options (headers, timeout)
$response = http_get('https://api.example.com/protected', [], [
    'headers' => [
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json'
    ],
    'timeout' => 30
]);

// Check response
if ($response['status'] === 200) {
    $data = json_decode($response['body'], true);
}

http_post()

Execute a POST request.

Signature:

function http_post(string $url, array $data = [], bool $isJson = true, array $options = []): array

Parameters:

  • $url (string): Request URL
  • $data (array): Request body data
  • $isJson (bool): Whether to send as JSON (default: true)
  • $options (array): Additional cURL options

Returns:

  • array: Response data

Examples:

// JSON POST request
$response = http_post('https://api.example.com/users', [
    'name' => 'John Doe',
    'email' => 'john@example.com'
]);

// Form-encoded POST request
$response = http_post('https://api.example.com/login', [
    'username' => 'john',
    'password' => 'secret'
], false); // Send as form data

// POST with authentication
$response = http_post('https://api.example.com/posts', [
    'title' => 'New Post',
    'content' => 'Post content'
], true, [
    'bearer_token' => $apiToken
]);

http_put()

Execute a PUT request.

Signature:

function http_put(string $url, array $data = [], bool $isJson = true, array $options = []): array

Examples:

// Update a resource
$response = http_put('https://api.example.com/users/1', [
    'name' => 'John Updated',
    'email' => 'john.updated@example.com'
]);

http_patch()

Execute a PATCH request.

Signature:

function http_patch(string $url, array $data = [], bool $isJson = true, array $options = []): array

Examples:

// Partial update
$response = http_patch('https://api.example.com/users/1', [
    'email' => 'newemail@example.com'
]);

http_delete()

Execute a DELETE request.

Signature:

function http_delete(string $url, array $data = [], array $options = []): array

Examples:

// Delete a resource
$response = http_delete('https://api.example.com/users/1');

// Delete with body
$response = http_delete('https://api.example.com/users/batch', [
    'ids' => [1, 2, 3]
]);

http_head()

Execute a HEAD request.

Signature:

function http_head(string $url, array $options = []): array

Examples:

// Check if resource exists
$response = http_head('https://example.com/file.pdf');

if ($response['status'] === 200) {
    echo "File exists";
    $contentLength = $response['headers']['Content-Length'] ?? null;
}

http_options()

Execute an OPTIONS request.

Signature:

function http_options(string $url, array $options = []): array

Examples:

// Check allowed methods
$response = http_options('https://api.example.com/users');
$allowedMethods = $response['headers']['Allow'] ?? '';

http_upload_file()

Upload a file via multipart/form-data.

Signature:

function http_upload_file(string $url, string $fieldName, string $filePath, array $additionalData = [], array $options = []): array

Parameters:

  • $url (string): Upload URL
  • $fieldName (string): Form field name for the file
  • $filePath (string): Path to the file to upload
  • $additionalData (array): Additional form fields
  • $options (array): Additional cURL options

Throws:

  • MachinjiriException: When file doesn't exist or upload fails

Examples:

// Upload a file
$response = http_upload_file(
    'https://api.example.com/upload',
    'document',
    '/path/to/document.pdf'
);

// Upload with additional data
$response = http_upload_file(
    'https://api.example.com/upload',
    'avatar',
    '/path/to/image.jpg',
    [
        'user_id' => 123,
        'description' => 'Profile picture'
    ],
    [
        'headers' => ['Authorization' => 'Bearer ' . $token]
    ]
);

http_download_file()

Download a file from a URL and save it locally.

Signature:

function http_download_file(string $url, string $savePath, array $options = []): array

Parameters:

  • $url (string): File URL
  • $savePath (string): Local path to save the file
  • $options (array): Additional cURL options

Throws:

  • MachinjiriException: When download fails

Examples:

// Download a file
$result = http_download_file(
    'https://example.com/document.pdf',
    '/path/to/save/document.pdf'
);

if ($result['success']) {
    echo "Downloaded to: " . $result['path'];
}

// Download with progress tracking
$result = http_download_file(
    'https://example.com/large-file.zip',
    storage_path('downloads/file.zip'),
    [
        'timeout' => 300,
        'headers' => ['Accept' => 'application/octet-stream']
    ]
);

http_multi_request()

Execute multiple HTTP requests concurrently.

Signature:

function http_multi_request(array $requests, array $globalOptions = []): array

Parameters:

  • $requests (array): Array of request configurations
  • $globalOptions (array): Options applied to all requests

Returns:

  • array: Results keyed by original request keys

Examples:

// Multiple concurrent requests
$responses = http_multi_request([
    'users' => [
        'url' => 'https://api.example.com/users',
        'options' => ['headers' => ['Accept' => 'application/json']]
    ],
    'posts' => [
        'url' => 'https://api.example.com/posts'
    ],
    'comments' => [
        'url' => 'https://api.example.com/comments'
    ]
], [
    'timeout' => 30,
    'headers' => ['Authorization' => 'Bearer ' . $token]
]);

// Access results
$users = $responses['users'];
$posts = $responses['posts'];
$comments = $responses['comments'];

http_api()

Execute a request and return an HttpResponse object.

Signature:

function http_api(string $url, ?string $method = null, $data = null, array $headers = []): HttpResponse

Examples:

// GET request
$response = http_api('https://api.example.com/users');

// POST request
$response = http_api('https://api.example.com/users', 'POST', [
    'name' => 'John'
]);

// With headers
$response = http_api(
    'https://api.example.com/protected',
    'GET',
    null,
    ['Authorization' => 'Bearer ' . $token]
);

// Access response
if ($response->isSuccessful()) {
    $data = $response->json();
}

apply_options()

Apply configuration options to an HttpClient instance.

Signature:

function apply_options(HttpClient $client, array $options): void

Supported Options:

Option Type Description
headers array HTTP headers
timeout int Request timeout in seconds
max_redirects int Maximum redirects to follow
user_agent string User-Agent header
referer string Referer header
basic_auth array [username, password]
bearer_token string Bearer token for auth
proxy array/string Proxy configuration
ssl array SSL options
retry array Retry configuration
compress bool Enable compression
cookies bool/string Cookie handling
cookie_pairs array Cookie name-value pairs
custom_method string Custom HTTP method
capture_headers bool Capture response headers

Examples:

$client = http_client();

apply_options($client, [
    'headers' => [
        'Accept' => 'application/json',
        'X-Custom-Header' => 'value'
    ],
    'timeout' => 60,
    'bearer_token' => $apiToken,
    'retry' => [
        'max_retries' => 3,
        'retry_delay' => 1000
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_host' => 2
    ]
]);

Routing Helpers

route_get()

Register a GET route.

Signature:

function route_get(string $pattern, mixed $handler, ?string $name = null, array $options = []): Router

Parameters:

  • $pattern (string): URL pattern
  • $handler (mixed): Route handler (closure, controller method, etc.)
  • $name (string|null): Route name for URL generation
  • $options (array): Additional route options

Examples:

// Simple route
route_get('/', function () {
    echo "Welcome!";
});

// Route with controller
route_get('/users', [UserController::class, 'index']);

// Named route
route_get('/users/{id}', [UserController::class, 'show'], 'users.show');

// With middleware
route_get('/admin', [AdminController::class, 'dashboard'], 'admin.dashboard', [
    'middleware' => ['auth', 'admin']
]);

// With parameters
route_get('/posts/{category}/{slug}', function ($category, $slug) {
    // Handle the request
});

route_post()

Register a POST route.

Signature:

function route_post(string $pattern, mixed $handler, ?string $name = null, array $options = []): Router

Examples:

// Handle form submission
route_post('/users', [UserController::class, 'store'], 'users.store');

// API endpoint
route_post('/api/users', function () {
    $data = json_decode(file_get_contents('php://input'), true);
    // Process data
});

route_put()

Register a PUT route.

Signature:

function route_put(string $pattern, mixed $handler, ?string $name = null, array $options = []): Router

Examples:

// Full resource update
route_put('/users/{id}', [UserController::class, 'update'], 'users.update');

route_delete()

Register a DELETE route.

Signature:

function route_delete(string $pattern, mixed $handler, ?string $name = null, array $options = []): Router

Examples:

// Delete resource
route_delete('/users/{id}', [UserController::class, 'destroy'], 'users.destroy');

route_any()

Register a route responding to any HTTP method.

Signature:

function route_any(string $pattern, mixed $handler, ?string $name = null, array $options = []): Router

Examples:

// Webhook endpoint accepting any method
route_any('/webhook', function () {
    // Handle webhook
});

route_ajax()

Register an AJAX-only route.

Signature:

function route_ajax(string $pattern, mixed $handler, ?string $name = null, array $options = []): Router

Examples:

// AJAX endpoint
route_ajax('/api/data', function () {
    return response()->json(['data' => 'value']);
});

route_traditional()

Register a traditional (non-AJAX) route.

Signature:

function route_traditional(string $pattern, mixed $handler, ?string $name = null, array $options = []): Router

Examples:

// Regular page route
route_traditional('/about', function () {
    view('pages.about');
});

route_group()

Create a route group with shared attributes.

Signature:

function route_group(array $attributes, callable $callback): Router

Parameters:

  • $attributes (array): Shared attributes (prefix, middleware, etc.)
  • $callback (callable): Group definition callback

Examples:

// Group with prefix
route_group(['prefix' => '/admin'], function () {
    route_get('/dashboard', [AdminController::class, 'dashboard']);
    route_get('/users', [AdminController::class, 'users']);
    route_get('/settings', [AdminController::class, 'settings']);
});

// Group with middleware
route_group(['middleware' => ['auth']], function () {
    route_get('/profile', [ProfileController::class, 'show']);
    route_post('/profile', [ProfileController::class, 'update']);
});

// Nested groups
route_group(['prefix' => '/api', 'middleware' => ['api']], function () {
    route_group(['prefix' => '/v1'], function () {
        route_get('/users', [ApiController::class, 'users']);
    });
});

route_middleware()

Apply middleware to a route or group.

Signature:

function route_middleware(mixed $middleware, ?callable $callback = null): Router

Examples:

// Apply to a route
route_middleware('auth', function () {
    route_get('/dashboard', [DashboardController::class, 'index']);
});

// Multiple middleware
route_middleware(['auth', 'verified'], function () {
    route_get('/settings', [SettingsController::class, 'index']);
});

route_cors()

Apply CORS configuration.

Signature:

function route_cors(array $config = [], ?callable $callback = null): Router

Examples:

// Apply CORS to routes
route_cors([
    'allowed_origins' => ['https://example.com'],
    'allowed_methods' => ['GET', 'POST'],
    'allowed_headers' => ['Content-Type', 'Authorization']
], function () {
    route_post('/api/data', [ApiController::class, 'data']);
});

base_url()

Get the base URL of the application.

Signature:

function base_url(): string

Examples:

$base = base_url(); // https://example.com

// Use in views
<link rel="canonical" href="<?= base_url() ?>/page">

route_url()

Generate a URL for a named route (relative).

Signature:

function route_url(string $name, array $params = []): string

Parameters:

  • $name (string): Route name
  • $params (array): Route parameters

Throws:

  • MachinjiriException: When route not found

Examples:

// Named route registration
route_get('/users/{id}', [UserController::class, 'show'], 'users.show');

// Generate URL
$url = route_url('users.show', ['id' => 1]); // /users/1

// In views
<a href="<?= route_url('users.show', ['id' => $user->id]) ?>">View User</a>

route_absolute()

Generate an absolute URL for a named route.

Signature:

function route_absolute(string $name, array $params = []): string

Examples:

// Generate absolute URL
$url = route_absolute('users.show', ['id' => 1]);
// https://example.com/users/1

// For email links
$resetLink = route_absolute('password.reset', ['token' => $token]);

dispatch_routes()

Dispatch the current request to the matching route.

Signature:

function dispatch_routes(): void

Examples:

// In index.php or entry point
require_once __DIR__ . '/../vendor/autoload.php';

// Bootstrap application
$app = require_once __DIR__ . '/../bootstrap/app.php';

// Register routes
require_once __DIR__ . '/../routes/web.php';

// Dispatch the request
dispatch_routes();

Security Helpers

csrf_token_instance()

Get the CSRFToken instance.

Signature:

function csrf_token_instance(): CSRFToken

Returns:

  • CSRFToken: The CSRF token handler instance

Examples:

$csrf = csrf_token_instance();

// Generate token
$token = $csrf->getToken();

// Validate token
if ($csrf->validate($requestToken)) {
    // Token is valid
}

// Regenerate token
$newToken = $csrf->regenerate();

csrf_token()

Get the current CSRF token string.

Signature:

function csrf_token(): string

Returns:

  • string: The CSRF token

Examples:

// Get token for AJAX requests
$token = csrf_token();

// Use in JavaScript
<script>
    window.csrfToken = '<?= csrf_token() ?>';
    
    fetch('/api/data', {
        method: 'POST',
        headers: {
            'X-CSRF-Token': window.csrfToken,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ data: 'value' })
    });
</script>

// Use in meta tag
<meta name="csrf-token" content="<?= csrf_token() ?>">

csrf_field()

Generate a hidden CSRF token input field.

Signature:

function csrf_field(): string

Returns:

  • string: HTML hidden input field

Examples:

// In a form
<form method="POST" action="/submit">
    <?= csrf_field() ?>
    <input type="text" name="name">
    <button type="submit">Submit</button>
</form>

// In a view
<form method="POST" action="<?= route_url('posts.store') ?>">
    <?= csrf_field() ?>
    <input type="text" name="title">
    <textarea name="content"></textarea>
    <button type="submit">Create Post</button>
</form>

View Helpers

view()

Render a view and output it (typed as void but displays content).

Signature:

function view(string $view, array $data = []): void

Parameters:

  • $view (string): View name (dot notation for directories)
  • $data (array): Data to pass to the view

Examples:

// Basic view
view('welcome');

// View with data
view('users.profile', [
    'user' => $user,
    'posts' => $posts
]);

// In controller
public function show($id)
{
    $user = query_builder('users')->find($id);
    
    if (!$user) {
        abort(404);
    }
    
    view('users.show', ['user' => $user]);
}

display_view()

Render and output a view.

Signature:

function display_view(string $view, array $data = []): void

Examples:

// Display a view
display_view('pages.about', ['title' => 'About Us']);

asset()

Generate a versioned asset URL.

Signature:

function asset(string $path): string

Parameters:

  • $path (string): Asset path relative to public directory

Returns:

  • string: Versioned asset URL

Throws:

  • MachinjiriException: When asset processing fails

Examples:

// Generate asset URL
$cssUrl = asset('css/app.css');
// /css/app.css?v=1.2.3

$jsUrl = asset('js/app.js');
// /js/app.js?v=2.0.0

// In views
<link rel="stylesheet" href="<?= asset('css/app.css') ?>">
<script src="<?= asset('js/app.js') ?>"></script>
<img src="<?= asset('images/logo.png') ?>" alt="Logo">

style()

Generate a <link> tag for a CSS asset.

Signature:

function style(string $path, array $attributes = []): void

Parameters:

  • $path (string): CSS file path
  • $attributes (array): Additional HTML attributes

Examples:

// In view header
<style>
    <?php style('css/app.css'); ?>
</style>

// Output: <link rel="stylesheet" href="/css/app.css">

// With attributes
<?php style('css/print.css', ['media' => 'print']); ?>
// <link rel="stylesheet" href="/css/print.css" media="print">

script()

Generate a <script> tag for a JavaScript asset.

Signature:

function script(string $path, array $attributes = []): void

Examples:

// In view footer
<?php script('js/app.js'); ?>
// <script src="/js/app.js"></script>

// With attributes
<?php script('js/analytics.js', ['async' => true, 'defer' => true]); ?>
// <script src="/js/analytics.js" async defer></script>

share()

Share data across all views.

Signature:

function share($key, $value = null): void

Parameters:

  • $key (string|array): Variable name or array of variables
  • $value (mixed): Variable value

Examples:

// Share a single variable
share('appName', 'My Application');

// Share multiple variables
share([
    'appName' => 'My Application',
    'appVersion' => '1.0.0',
    'currentYear' => date('Y')
]);

// Share current user (typically in middleware)
share('currentUser', auth()->user());

// Now accessible in all views

section()

Start or set a named section in views.

Signature:

function section(string $name, ?string $content = null): void

Parameters:

  • $name (string): Section name
  • $content (string|null): Direct content or null to start buffering

Examples:

// In layout file
<html>
<head>
    <title><?= $title ?? 'Default Title' ?></title>
    <?php view_yield('styles'); ?>
</head>
<body>
    <?php view_yield('content'); ?>
    
    <?php view_yield('scripts'); ?>
</body>
</html>

// In child view
<?php section('styles'); ?>
<link rel="stylesheet" href="/css/page.css">
<?php endSection(); ?>

<?php section('content'); ?>
<h1>Welcome</h1>
<p>Page content here.</p>
<?php endSection(); ?>

<?php section('scripts'); ?>
<script src="/js/page.js"></script>
<?php endSection(); ?>

// Direct content setting
<?php section('title', 'My Page Title'); ?>

endSection()

End the currently open section.

Signature:

function endSection(): void

Examples:

<?php section('content'); ?>
    <h1>Page Content</h1>
    <p>Lorem ipsum...</p>
<?php endSection(); ?>

view_yield()

Output the content of a section.

Signature:

function view_yield(string $name): void

Examples:

// In layout
<head>
    <?php view_yield('head'); ?>
</head>
<body>
    <main>
        <?php view_yield('content'); ?>
    </main>
    <footer>
        <?php view_yield('footer'); ?>
    </footer>
</body>

extend()

Specify a layout to extend.

Signature:

function extend(string $layout): void

Examples:

// In child view
<?php extend('layouts.app'); ?>

<?php section('content'); ?>
    <h1>Child Page</h1>
<?php endSection(); ?>

include_view()

Include a partial view.

Signature:

function include_view(string $view, array $data = []): void

Examples:

// Include a header partial
<?php include_view('partials.header'); ?>

// Include with data
<?php include_view('partials.user-card', ['user' => $user]); ?>

// Include sidebar with multiple data
<?php include_view('partials.sidebar', [
    'categories' => $categories,
    'recentPosts' => $recentPosts
]); ?>

hasSection()

Check if a section exists.

Signature:

function hasSection(string $name): bool

Examples:

// In layout
<?php if (hasSection('sidebar')): ?>
    <aside>
        <?php view_yield('sidebar'); ?>
    </aside>
<?php endif; ?>

getSection()

Get section content without outputting.

Signature:

function getSection(string $name): string

Examples:

// Get section content
$sidebarContent = getSection('sidebar');

if (!empty($sidebarContent)) {
    echo '<aside>' . $sidebarContent . '</aside>';
}

parent()

Output parent section content when using inheritance.

Signature:

function parent(): void

Examples:

// In layout
<?php section('scripts'); ?>
    <script src="/js/app.js"></script>
<?php endSection(); ?>

// In child view
<?php section('scripts'); ?>
    <?php parent(); ?>
    <script src="/js/page-specific.js"></script>
<?php endSection(); ?>

Best Practices

1. Use Helpers Appropriately

// Good: Use config() for configuration
$timezone = config('app.timezone', 'UTC');

// Good: Use env() for environment variables
$debug = env('APP_DEBUG', false);

// Bad: Mixing concerns
$timezone = env('APP_TIMEZONE', config('app.timezone', 'UTC')); // Avoid this

2. Prefer Dependency Injection for Testability

// Good: DI makes testing easier
class UserService {
    public function __construct(
        private QueryBuilder $db,
        private CacheManager $cache
    ) {}
}

// Less ideal: Using resolve() makes mocking harder
class UserService {
    public function getUsers() {
        $db = resolve(QueryBuilder::class);
        // ...
    }
}

3. Use Named Routes for URL Generation

// Good: Named routes are maintainable
route_get('/users/{id}', [UserController::class, 'show'], 'users.show');
$url = route_url('users.show', ['id' => 1]);

// Bad: Hardcoded URLs are fragile
$url = '/users/' . $id;

4. Always Use CSRF Protection in Forms

// Good: Always include CSRF token
<form method="POST">
    <?= csrf_field() ?>
    <!-- form fields -->
</form>

// Bad: Missing CSRF protection
<form method="POST">
    <!-- form fields -->
</form>

5. Use Dot Notation for Configuration

// Good: Dot notation
$host = config('database.connections.mysql.host');

// Bad: Manual array access
$config = config();
$host = $config['database']['connections']['mysql']['host'];

6. Cache Expensive Operations

// Good: Cache database results
$users = cache_manager()->remember('users.active', 3600, function () {
    return query_builder('users')->where('status', 'active')->get();
});

// Or use cached query builder
$users = cached_query_builder('users')
    ->cacheFor(3600)
    ->where('status', 'active')
    ->get();

7. Use Debug Helpers During Development

// Good: Remove before production
dump($query, $bindings);  // Continue execution
dd($response);            // Stop execution

// Production: Use proper logging
debug('Processing order', ['order_id' => $order->id]);

8. Use Appropriate Path Helpers

// Good: Use path helpers
$config = config_path('app.php');
$log = storage_path('logs/app.log');

// Bad: Hardcoded paths
$config = __DIR__ . '/../config/app.php';
$log = __DIR__ . '/../storage/logs/app.log';

Quick Reference

Application

Helper Description
app() Get container or resolve service
resolve() Resolve service with parameters
singleton() Register singleton service
bind() Register service binding
alias() Create service alias
service() Get service provider

Configuration

Helper Description
config() Get/set configuration values
app_configurations() Get all configurations
config_path() Get config file path

Paths

Helper Description
base_path() Application root path
app_path() App directory path
public_path() Public directory path
resource_path() Resources directory path
storage_path() Storage directory path
database_path() Database directory path

Environment

Helper Description
env() Get environment variable

Cache & Database

Helper Description
cache_manager() Get cache manager
query_builder() Create query builder
cached_query_builder() Create cached query builder

Date & Time

Helper Description
datetime_handler() Get date/time handler
now() Get current date/time string

Debugging

Helper Description
dump() Dump and continue
dd() Dump and die
debugger() Get debugger instance
debug() Log debug message
measure() Measure execution time

Events

Helper Description
event() Trigger event or register listener

HTTP

Helper Description
http_client() Create HTTP client
http_get() GET request
http_post() POST request
http_put() PUT request
http_patch() PATCH request
http_delete() DELETE request
http_head() HEAD request
http_options() OPTIONS request
http_upload_file() Upload file
http_download_file() Download file
http_multi_request() Concurrent requests
http_api() API request
apply_options() Apply HTTP options

Routing

Helper Description
route_get() Register GET route
route_post() Register POST route
route_put() Register PUT route
route_delete() Register DELETE route
route_any() Register any-method route
route_ajax() Register AJAX route
route_traditional() Register traditional route
route_group() Create route group
route_middleware() Apply middleware
route_cors() Apply CORS config
base_url() Get base URL
route_url() Generate relative URL
route_absolute() Generate absolute URL
dispatch_routes() Dispatch current request

Security

Helper Description
csrf_token_instance() Get CSRF instance
csrf_token() Get CSRF token string
csrf_field() Generate hidden input field

Views

Helper Description
view() Render and display view
display_view() Display a view
asset() Generate asset URL
style() Output CSS link tag
script() Output JS script tag
share() Share data across views
section() Start/set section
endSection() End current section
view_yield() Output section content
extend() Extend layout
include_view() Include partial view
hasSection() Check section exists
getSection() Get section content
parent() Output parent section

Additional Resources

Framework Structure

project/
├── app/
│   ├── Controllers/
│   ├── Models/
│   └── Middleware/
├── bootstrap/
│   └── app.php
├── config/
│   ├── app.php
│   ├── database.php
│   └── cache.php
├── database/
│   ├── migrations/
│   └── seeds/
├── public/
│   ├── css/
│   ├── js/
│   └── index.php
├── resources/
│   └── views/
├── routes/
│   └── web.php
├── storage/
│   ├── logs/
│   ├── cache/
│   └── sessions/
└── vendor/

Common Patterns

Service Registration

// In a ServiceProvider
public function register(): void
{
    singleton(Logger::class, FileLogger::class);
    singleton(CacheManager::class, function ($app) {
        return new CacheManager(config('cache'));
    });
    
    bind(MailerInterface::class, SmtpMailer::class);
}

Route Organization

// routes/web.php

// Public routes
route_get('/', [HomeController::class, 'index'], 'home');
route_get('/about', [PageController::class, 'about'], 'about');

// Auth routes
route_group(['prefix' => '/auth'], function () {
    route_get('/login', [AuthController::class, 'showLogin'], 'login');
    route_post('/login', [AuthController::class, 'login']);
    route_get('/register', [AuthController::class, 'showRegister'], 'register');
    route_post('/register', [AuthController::class, 'register']);
    route_post('/logout', [AuthController::class, 'logout'], 'logout');
});

// Protected routes
route_group(['middleware' => ['auth']], function () {
    route_get('/dashboard', [DashboardController::class, 'index'], 'dashboard');
    route_get('/profile', [ProfileController::class, 'show'], 'profile');
    route_post('/profile', [ProfileController::class, 'update']);
});

View Usage

// In controller
public function index()
{
    $users = query_builder('users')->get();
    
    share('pageTitle', 'User List');
    
    view('users.index', [
        'users' => $users
    ]);
}

Cache Usage

// Cache expensive operation
$stats = cache_manager()->remember('dashboard.stats', 300, function () {
    return [
        'users' => query_builder('users')->count(),
        'posts' => query_builder('posts')->count(),
        'comments' => query_builder('comments')->count()
    ];
});

Troubleshooting

Common Issues

Issue: Call to undefined function config() Solution: Ensure the framework's helper files are loaded in your bootstrap file:

require_once __DIR__ . '/../vendor/machinjiri/helpers/app.php';
require_once __DIR__ . '/../vendor/machinjiri/helpers/config.php';
// etc.

Issue: Application container not initialized Solution: Initialize the container before using helpers:

$container = new Container();
$GLOBALS['__machinjiri_container'] = $container;

Issue: Class not found when using resolve() Solution: Ensure the class is bound in the container or has proper namespace:

// Check binding
if (app()->bound(MyService::class)) {
    $service = app(MyService::class);
}

Issue: Assets not loading Solution: Check the public directory path and asset() helper configuration:

// Verify asset path
$url = asset('css/app.css');
// Ensure file exists at public/css/app.css

Issue: CSRF token validation failing Solution: Ensure sessions are started and csrf_field() is included:

session_start();
// In form:
echo csrf_field();

Conclusion

The Machinjiri Framework's helper functions provide a powerful, convenient API for common development tasks. From container management to database queries, from HTTP requests to view rendering, these helpers streamline your workflow and reduce boilerplate code.

Remember:

  • Use helpers appropriately — they're tools, not replacements for good architecture
  • Prefer dependency injection for testable, maintainable code
  • Follow the patterns shown in this documentation
  • Refer to this guide when working with unfamiliar helpers

Clone this wiki locally