Repository navigation
Helper Function
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.
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.
- 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
- Machinjiri Framework installed and configured
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);Get the application container instance or resolve a service.
Signature:
function app(?string $abstract = null): Container|mixedParameters:
-
$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 a service from the container with optional parameters.
Signature:
function resolve(string $abstract, array $parameters = []): mixedParameters:
-
$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
]);Register a singleton service in the container. Singletons are instantiated once and reused.
Signature:
function singleton(string $abstract, $concrete = null): voidParameters:
-
$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);Register a binding in the container.
Signature:
function bind(string $abstract, $concrete = null, bool $shared = false): voidParameters:
-
$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);Register an alias for a service.
Signature:
function alias(string $abstract, string $alias): voidParameters:
-
$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);Get a service provider instance.
Signature:
function service(string $providerClass): ?ServiceProviderParameters:
-
$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();
}Check if a service provider is registered.
Signature:
function service_provider(string $providerClass): boolParameters:
-
$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 a specific service provider.
Signature:
function boot_service_provider(string $providerClass): boolParameters:
-
$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!";
}Get or set configuration values using dot notation.
Signature:
function config($key = null, $default = null): mixedParameters:
-
$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']);Get application configurations from the container.
Signature:
function app_configurations(string $key = ''): arrayParameters:
-
$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');Get the full path to a configuration file.
Signature:
function config_path(string $filename = ''): stringParameters:
-
$filename(string): Configuration filename (with or without.phpextension)
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');Get the base path of the application.
Signature:
function base_path(string $path = ''): stringParameters:
-
$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.jsonGet the path to the application directory.
Signature:
function app_path(string $path = ''): stringExamples:
// Get app directory
$appDir = app_path(); // /var/www/myapp/app
// Get path to a controller
$controller = app_path('Controllers/UserController.php');Get the path to the public directory.
Signature:
function public_path(string $path = ''): stringExamples:
// Get public directory
$public = public_path(); // /var/www/myapp/public
// Get path to CSS file
$css = public_path('css/app.css');Get the path to the resources directory.
Signature:
function resource_path(string $path = ''): stringExamples:
// Get resources directory
$resources = resource_path(); // /var/www/myapp/resources
// Get path to view
$view = resource_path('views/welcome.php');Get the path to the storage directory.
Signature:
function storage_path(string $path = ''): stringExamples:
// 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');Get the path to the database directory.
Signature:
function database_path(string $path = ''): stringExamples:
// 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');Get environment variable values.
Signature:
function env(string $key, $default = null): mixedParameters:
-
$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=secretGet the CacheManager instance.
Signature:
function cache_manager(): CacheManagerReturns:
-
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');Create a new QueryBuilder instance.
Signature:
function query_builder(string $table = ''): QueryBuilderParameters:
-
$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();Create a new CachedQueryBuilder instance for automatic query result caching.
Signature:
function cached_query_builder(string $table = ''): CachedQueryBuilderParameters:
-
$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();Get a DateTimeHandler instance.
Signature:
function datetime_handler(?string $timezone = null): DateTimeHandlerParameters:
-
$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 agoGet current date and time.
Signature:
function now(string $format = ''): stringParameters:
-
$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()
]);Dump variables for inspection and continue execution.
Signature:
function dump(...$args): voidParameters:
-
...$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);Dump variables and terminate the script (die and dump).
Signature:
function dd(...$args): neverParameters:
-
...$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);
}Get the Debugger instance.
Signature:
function debugger(): DebuggerReturns:
-
Debugger: The debugger singleton instance
Examples:
// Get debugger instance
$debugger = debugger();
// Access debugger methods
debugger()->startTimer('operation');
// ... code to measure ...
debugger()->endTimer('operation');Log a debug message.
Signature:
function debug($message, array $context = []): voidParameters:
-
$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 execution time of a callable.
Signature:
function measure(callable $callback, string $label = 'anonymous'): mixedParameters:
-
$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');Trigger an event or register an event listener.
Signature:
function event(string $event, $data = null): void|mixedParameters:
-
$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'
]);Create a new HttpClient instance.
Signature:
function http_client(string $baseUrl = '', ?Session $session = null, ?Cookie $cookie = null): HttpClientParameters:
-
$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']);Execute a GET request.
Signature:
function http_get(string $url, array $queryParams = [], array $options = []): arrayParameters:
-
$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);
}Execute a POST request.
Signature:
function http_post(string $url, array $data = [], bool $isJson = true, array $options = []): arrayParameters:
-
$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
]);Execute a PUT request.
Signature:
function http_put(string $url, array $data = [], bool $isJson = true, array $options = []): arrayExamples:
// Update a resource
$response = http_put('https://api.example.com/users/1', [
'name' => 'John Updated',
'email' => 'john.updated@example.com'
]);Execute a PATCH request.
Signature:
function http_patch(string $url, array $data = [], bool $isJson = true, array $options = []): arrayExamples:
// Partial update
$response = http_patch('https://api.example.com/users/1', [
'email' => 'newemail@example.com'
]);Execute a DELETE request.
Signature:
function http_delete(string $url, array $data = [], array $options = []): arrayExamples:
// 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]
]);Execute a HEAD request.
Signature:
function http_head(string $url, array $options = []): arrayExamples:
// 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;
}Execute an OPTIONS request.
Signature:
function http_options(string $url, array $options = []): arrayExamples:
// Check allowed methods
$response = http_options('https://api.example.com/users');
$allowedMethods = $response['headers']['Allow'] ?? '';Upload a file via multipart/form-data.
Signature:
function http_upload_file(string $url, string $fieldName, string $filePath, array $additionalData = [], array $options = []): arrayParameters:
-
$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]
]
);Download a file from a URL and save it locally.
Signature:
function http_download_file(string $url, string $savePath, array $options = []): arrayParameters:
-
$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']
]
);Execute multiple HTTP requests concurrently.
Signature:
function http_multi_request(array $requests, array $globalOptions = []): arrayParameters:
-
$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'];Execute a request and return an HttpResponse object.
Signature:
function http_api(string $url, ?string $method = null, $data = null, array $headers = []): HttpResponseExamples:
// 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 configuration options to an HttpClient instance.
Signature:
function apply_options(HttpClient $client, array $options): voidSupported 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
]
]);Register a GET route.
Signature:
function route_get(string $pattern, mixed $handler, ?string $name = null, array $options = []): RouterParameters:
-
$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
});Register a POST route.
Signature:
function route_post(string $pattern, mixed $handler, ?string $name = null, array $options = []): RouterExamples:
// 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
});Register a PUT route.
Signature:
function route_put(string $pattern, mixed $handler, ?string $name = null, array $options = []): RouterExamples:
// Full resource update
route_put('/users/{id}', [UserController::class, 'update'], 'users.update');Register a DELETE route.
Signature:
function route_delete(string $pattern, mixed $handler, ?string $name = null, array $options = []): RouterExamples:
// Delete resource
route_delete('/users/{id}', [UserController::class, 'destroy'], 'users.destroy');Register a route responding to any HTTP method.
Signature:
function route_any(string $pattern, mixed $handler, ?string $name = null, array $options = []): RouterExamples:
// Webhook endpoint accepting any method
route_any('/webhook', function () {
// Handle webhook
});Register an AJAX-only route.
Signature:
function route_ajax(string $pattern, mixed $handler, ?string $name = null, array $options = []): RouterExamples:
// AJAX endpoint
route_ajax('/api/data', function () {
return response()->json(['data' => 'value']);
});Register a traditional (non-AJAX) route.
Signature:
function route_traditional(string $pattern, mixed $handler, ?string $name = null, array $options = []): RouterExamples:
// Regular page route
route_traditional('/about', function () {
view('pages.about');
});Create a route group with shared attributes.
Signature:
function route_group(array $attributes, callable $callback): RouterParameters:
-
$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']);
});
});Apply middleware to a route or group.
Signature:
function route_middleware(mixed $middleware, ?callable $callback = null): RouterExamples:
// 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']);
});Apply CORS configuration.
Signature:
function route_cors(array $config = [], ?callable $callback = null): RouterExamples:
// 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']);
});Get the base URL of the application.
Signature:
function base_url(): stringExamples:
$base = base_url(); // https://example.com
// Use in views
<link rel="canonical" href="<?= base_url() ?>/page">Generate a URL for a named route (relative).
Signature:
function route_url(string $name, array $params = []): stringParameters:
-
$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>Generate an absolute URL for a named route.
Signature:
function route_absolute(string $name, array $params = []): stringExamples:
// 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 the current request to the matching route.
Signature:
function dispatch_routes(): voidExamples:
// 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();Get the CSRFToken instance.
Signature:
function csrf_token_instance(): CSRFTokenReturns:
-
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();Get the current CSRF token string.
Signature:
function csrf_token(): stringReturns:
-
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() ?>">Generate a hidden CSRF token input field.
Signature:
function csrf_field(): stringReturns:
-
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>Render a view and output it (typed as void but displays content).
Signature:
function view(string $view, array $data = []): voidParameters:
-
$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]);
}Render and output a view.
Signature:
function display_view(string $view, array $data = []): voidExamples:
// Display a view
display_view('pages.about', ['title' => 'About Us']);Generate a versioned asset URL.
Signature:
function asset(string $path): stringParameters:
-
$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">Generate a <link> tag for a CSS asset.
Signature:
function style(string $path, array $attributes = []): voidParameters:
-
$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">Generate a <script> tag for a JavaScript asset.
Signature:
function script(string $path, array $attributes = []): voidExamples:
// 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 data across all views.
Signature:
function share($key, $value = null): voidParameters:
-
$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 viewsStart or set a named section in views.
Signature:
function section(string $name, ?string $content = null): voidParameters:
-
$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'); ?>End the currently open section.
Signature:
function endSection(): voidExamples:
<?php section('content'); ?>
<h1>Page Content</h1>
<p>Lorem ipsum...</p>
<?php endSection(); ?>Output the content of a section.
Signature:
function view_yield(string $name): voidExamples:
// In layout
<head>
<?php view_yield('head'); ?>
</head>
<body>
<main>
<?php view_yield('content'); ?>
</main>
<footer>
<?php view_yield('footer'); ?>
</footer>
</body>Specify a layout to extend.
Signature:
function extend(string $layout): voidExamples:
// In child view
<?php extend('layouts.app'); ?>
<?php section('content'); ?>
<h1>Child Page</h1>
<?php endSection(); ?>Include a partial view.
Signature:
function include_view(string $view, array $data = []): voidExamples:
// 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
]); ?>Check if a section exists.
Signature:
function hasSection(string $name): boolExamples:
// In layout
<?php if (hasSection('sidebar')): ?>
<aside>
<?php view_yield('sidebar'); ?>
</aside>
<?php endif; ?>Get section content without outputting.
Signature:
function getSection(string $name): stringExamples:
// Get section content
$sidebarContent = getSection('sidebar');
if (!empty($sidebarContent)) {
echo '<aside>' . $sidebarContent . '</aside>';
}Output parent section content when using inheritance.
Signature:
function parent(): voidExamples:
// 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(); ?>// 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// 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);
// ...
}
}// 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;// Good: Always include CSRF token
<form method="POST">
<?= csrf_field() ?>
<!-- form fields -->
</form>
// Bad: Missing CSRF protection
<form method="POST">
<!-- form fields -->
</form>// Good: Dot notation
$host = config('database.connections.mysql.host');
// Bad: Manual array access
$config = config();
$host = $config['database']['connections']['mysql']['host'];// 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();// Good: Remove before production
dump($query, $bindings); // Continue execution
dd($response); // Stop execution
// Production: Use proper logging
debug('Processing order', ['order_id' => $order->id]);// 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';| 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 |
| Helper | Description |
|---|---|
config() |
Get/set configuration values |
app_configurations() |
Get all configurations |
config_path() |
Get config file path |
| 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 |
| Helper | Description |
|---|---|
env() |
Get environment variable |
| Helper | Description |
|---|---|
cache_manager() |
Get cache manager |
query_builder() |
Create query builder |
cached_query_builder() |
Create cached query builder |
| Helper | Description |
|---|---|
datetime_handler() |
Get date/time handler |
now() |
Get current date/time string |
| Helper | Description |
|---|---|
dump() |
Dump and continue |
dd() |
Dump and die |
debugger() |
Get debugger instance |
debug() |
Log debug message |
measure() |
Measure execution time |
| Helper | Description |
|---|---|
event() |
Trigger event or register listener |
| 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 |
| 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 |
| Helper | Description |
|---|---|
csrf_token_instance() |
Get CSRF instance |
csrf_token() |
Get CSRF token string |
csrf_field() |
Generate hidden input field |
| 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 |
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/
// 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);
}// 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']);
});// In controller
public function index()
{
$users = query_builder('users')->get();
share('pageTitle', 'User List');
view('users.index', [
'users' => $users
]);
}// 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()
];
});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.cssIssue: CSRF token validation failing Solution: Ensure sessions are started and csrf_field() is included:
session_start();
// In form:
echo csrf_field();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
Machinjiri Docs
- Home
- Learn
- Build
-
Tutorials
- Routing
- Controllers and Middleware
- Views and Templates
- Database ORM
- Eloquent Database ORM
- Errors and Exceptions
- Forms and Validation
- Http
- Events and Logging
- Services and DI
- Security
- Authentication
- Caching
- File System
- Date and Time
- Debugging
- Queue and Jobs
- Task Scheduling
- Transport (Mail, SMS)
- LDAP
- Notifications
- Webhooks
- UUID Generations
- Terminal
- Helper Function
- Reference