Skip to main content

Helper Functions Reference

Mumara Campaigns provides a set of helper functions that simplify working with hooks. These functions wrap the core Hooks class and provide convenient shortcuts for common operations.

Registration Functions

add_hook()

Registers a callback function to be executed when a specific hook is fired.

add_hook(string $hook, int $priority, callable $function): void

Parameters:

ParameterTypeDescription
$hookstringThe hook name to attach to
$priorityintExecution priority (lower numbers run first)
$functioncallableCallback function to execute

Example:

// Using anonymous function
add_hook('AddContact', 1, function($vars) {
Log::info('Contact added', $vars);
});

// Using named function
function my_contact_handler($vars) {
Log::info('Contact added', $vars);
}
add_hook('AddContact', 1, 'my_contact_handler');

// Using class method
add_hook('AddContact', 1, [MyClass::class, 'handleContact']);

Execution Functions

listen_hook()

Executes all callbacks registered to a hook synchronously (immediately).

listen_hook(string $hook, mixed $arg = ''): void

Parameters:

ParameterTypeDescription
$hookstringThe hook name to execute
$argmixedData to pass to callbacks (usually array)

Example:

// Fire hook with data
listen_hook('AddContact', [
'subscriber_id' => $contact->id,
'email' => $contact->email,
'list_id' => $listId
]);

// Fire hook without data
listen_hook('AfterCron');

Behavior:

  • Executes all registered callbacks in priority order
  • Blocks until all callbacks complete
  • Errors are caught and logged (if error logging is enabled)

run_hook_in_background()

Queues a hook for background execution via Laravel's queue system.

run_hook_in_background(string $hook, mixed $arg = ''): void

Parameters:

ParameterTypeDescription
$hookstringThe hook name to execute
$argmixedData to pass to callbacks

Example:

// Queue hook for background processing
run_hook_in_background('EmailSentPostProcess', [
'campaign_id' => $campaign->id,
'subscriber_id' => $subscriber->id,
'log_id' => $logId
]);

Behavior:

  • Checks if hook has registered callbacks before queuing
  • Creates a ListenHook job in the queue
  • Non-blocking - returns immediately
  • Ideal for time-consuming operations

When to Use:

  • Sending notifications to external services
  • Heavy data processing
  • Operations that shouldn't delay user response
  • Logging to external systems

Retrieval Functions

hook_get_output()

Returns the concatenated string output from all callbacks registered to a hook.

hook_get_output(string $hook, mixed $arg = ''): string

Parameters:

ParameterTypeDescription
$hookstringThe hook name
$argmixedData to pass to callbacks

Returns: Concatenated string from all callback returns

Example:

// In a Blade template
{!! hook_get_output('HeadTop', ['route' => Route::currentRouteName()]) !!}

// In PHP
$footerHtml = hook_get_output('Footer', $vars);
echo $footerHtml;

Behavior:

  • Executes all callbacks in priority order
  • Concatenates all return values into a single string
  • Returns empty string if no callbacks are registered

hook_get()

Returns the result from the first callback registered to a hook.

hook_get(string $hook, mixed $arg = []): mixed

Parameters:

ParameterTypeDescription
$hookstringThe hook name
$argmixedData to pass to callback

Returns: The return value from the first (lowest priority) callback

Example:

// Get a single computed value
$customTitle = hook_get('PageTitle', ['page' => 'dashboard']);

if ($customTitle) {
$title = $customTitle;
}

Behavior:

  • Only executes the first callback (lowest priority number)
  • Useful when you only need one result
  • Returns null if no callbacks are registered

hook_get_all()

Returns an array containing the results from all callbacks registered to a hook.

hook_get_all(string $hook, mixed $arg = []): array

Parameters:

ParameterTypeDescription
$hookstringThe hook name
$argmixedData to pass to callbacks

Returns: Array of return values from all callbacks

Example:

// Get all menu items from different addons
$menuItems = hook_get_all('PrimaryMenu', $vars);

foreach ($menuItems as $item) {
echo $item;
}

// Get all validation results
$validations = hook_get_all('ValidateContact', ['email' => $email]);
$errors = array_filter($validations); // Get non-empty results

Behavior:

  • Executes all callbacks in priority order
  • Returns array indexed by execution order
  • Returns empty array if no callbacks are registered

Utility Functions

hook_exist()

Checks whether any callbacks are registered for a specific hook.

hook_exist(string $hook): bool

Parameters:

ParameterTypeDescription
$hookstringThe hook name to check

Returns: true if at least one callback is registered, false otherwise

Example:

// Only process if hooks are registered
if (hook_exist('AddContact')) {
run_hook_in_background('AddContact', $contactData);
}

// Conditional rendering
if (hook_exist('CustomWidget')) {
echo '<div class="widget-container">';
echo hook_get_output('CustomWidget', $vars);
echo '</div>';
}

Use Cases:

  • Avoid unnecessary processing when no hooks are registered
  • Conditionally render wrapper elements
  • Performance optimization

Core Hooks Class

For advanced usage, you can interact with the Hooks class directly.

Hooks::add_hook()

Static method to register a hook.

Hooks::add_hook(string $hook, int $priority, callable $function): void

Hooks::exist()

Static method to check if a hook has callbacks.

Hooks::exist(string $hook): bool

Hooks::listen()

Static method to execute hook callbacks.

Hooks::listen(string $hook, array $args = []): void

Hooks::getOutput()

Static method to get concatenated output.

Hooks::getOutput(string $hook, array $args = []): string

Hooks::get()

Static method to get first callback result.

Hooks::get(string $hook, array $args = []): mixed

Hooks::get_all()

Static method to get all callback results.

Hooks::get_all(string $hook, array $args = []): array

Error Handling

All helper functions include built-in error handling. When enable_hooks_error_logging is enabled in Application Settings, errors are automatically logged.

Error Logging Format

// Logged to storage/logs/laravel.log
"You have an error in hook 'HookName': Error message here"

Manual Error Handling

For critical hooks, add your own error handling:

add_hook('CriticalOperation', 1, function($vars) {
try {
// Your code
riskyOperation($vars);
} catch (Exception $e) {
Log::error('Critical hook failed', [
'hook' => 'CriticalOperation',
'error' => $e->getMessage(),
'vars' => $vars
]);

// Optionally notify administrators
notifyAdmin('Hook failure', $e->getMessage());

// Don't re-throw to allow other hooks to continue
}
});

Function Comparison

FunctionExecutionReturnsUse Case
listen_hook()SyncvoidFire events, trigger actions
run_hook_in_background()AsyncvoidHeavy processing, external APIs
hook_get_output()SyncstringRender HTML/content
hook_get()SyncmixedGet single value
hook_get_all()SyncarrayCollect multiple values
hook_exist()-boolCheck before processing

Common Patterns

Pattern 1: Conditional Hook Execution

// Only fire hook if it has listeners
if (hook_exist('CustomEvent')) {
listen_hook('CustomEvent', $data);
}

Pattern 2: Background Processing with Fallback

// Try background, fall back to sync
if (config('queue.default') !== 'sync') {
run_hook_in_background('HeavyProcess', $data);
} else {
listen_hook('HeavyProcess', $data);
}

Pattern 3: Aggregating Output with Wrapper

$content = hook_get_output('WidgetContent', $vars);

if (!empty($content)) {
echo '<div class="widget-wrapper">';
echo $content;
echo '</div>';
}

Pattern 4: Validation Chain

$errors = hook_get_all('ValidateInput', ['input' => $userInput]);
$errors = array_filter($errors); // Remove empty results

if (!empty($errors)) {
return response()->json(['errors' => $errors], 422);
}

Pattern 5: Priority-Based Override

// Default handler (high priority number = runs last)
add_hook('GetTitle', 100, function($vars) {
return 'Default Title';
});

// Custom override (low priority = runs first, returned by hook_get)
add_hook('GetTitle', 1, function($vars) {
return 'Custom Title';
});

// hook_get returns 'Custom Title' (first result)
$title = hook_get('GetTitle', $vars);