VOOZH about

URL: https://deepwiki.com/hypervel/foundation/2.4-global-helper-functions

⇱ Global Helper Functions | hypervel/foundation | DeepWiki


Loading...
Last indexed: 7 February 2026 (101eff)
Menu

Global Helper Functions

This page documents the global helper functions provided by the Hypervel Foundation package. These functions offer convenient static access to framework services and utilities without requiring explicit dependency injection. They serve as a facade layer that delegates to the Application Container and other framework components.

For information about the Application Container and service resolution, see Application Container and Dependency Injection. For details about application path resolution methods, see Application Paths and Environment Detection.


Overview

Global helper functions in Hypervel are defined in src/helpers.php1-815 and provide a Laravel-like API for accessing framework services. Each helper function is conditionally defined using function_exists() checks to prevent redefinition conflicts. The helpers follow a delegation pattern where they:

  1. Access the Application Container via ApplicationContext::getContainer() or the app() helper
  2. Resolve the appropriate service from the container
  3. Optionally perform additional operations or transformations
  4. Return the result to the caller

This approach provides developer convenience while maintaining the benefits of dependency injection and service location patterns used throughout the framework.

Sources: src/helpers.php1-815


Helper Function Architecture


Sources: src/helpers.php347-380 src/helpers.php526-548 src/helpers.php274-287 src/helpers.php289-305


Core Container Access

The app() Helper

The app() function is the foundational helper that provides access to the Application Container. All other helpers either directly or indirectly depend on it.

























FunctionSignatureReturnsDescription
app()app(?string $abstract = null, array $parameters = [])Application|mixedReturns the Application Container if no arguments provided, otherwise resolves the given abstract from the container
resolve()resolve(string $name, array $parameters = [])mixedAlias for app() that explicitly conveys service resolution intent

Sources: src/helpers.php347-380 src/helpers.php510-524


Path Resolution Helpers

Path helpers provide consistent access to application directory paths. These helpers have fallback logic when the container is unavailable, using the BASE_PATH constant.





























































FunctionPath ResolvedDelegates ToFallback
base_path()Base installation directoryapp()->basePath()BASE_PATH constant
app_path()Application source codejoin_paths(base_path('app'))N/A
database_path()Database files and migrationsapp()->databasePath()BASE_PATH/database
storage_path()Storage directoryapp()->storagePath()BASE_PATH/storage
config_path()Configuration filesapp()->configPath()BASE_PATH/config
resource_path()Resource files (views, assets)app()->resourcePath()BASE_PATH/resources
lang_path()Translation filesapp()->langPath()BASE_PATH/lang
public_path()Public web rootapp()->publicPath()BASE_PATH/public

Sources: src/helpers.php99-229


HTTP Request and Response Helpers

Request Access

FunctionSignatureReturnsDescription
request()request(array|string|null $key = null, mixed $default = null)RequestContract|mixed|arrayReturns the current request instance, or retrieves input values

The request() helper provides three modes of operation:

  • No arguments: Returns the RequestContract instance
  • String key: Returns $request->input($key, $default)
  • Array of keys: Returns $request->inputs($keys, $default)

Sources: src/helpers.php526-548

Response Creation

FunctionSignatureReturnsDescription
response()response(mixed $content = null, int $status = 200, array $headers = [])ResponseContract|ResponseInterfaceCreates a new response or returns the response factory
redirect()redirect(string $toUrl, int $status = 302, string $schema = 'http')ResponseInterfaceCreates a redirect response
to_route()to_route(string $route, array $parameters = [], int $status = 302, array $headers = [])ResponseInterfaceCreates a redirect to a named route

Sources: src/helpers.php550-594

Exception Helpers



























FunctionSignatureDescription
abort()abort(int|Responsable $code, string $message = '', array $headers = [])Throws an HTTP exception with the given status code
abort_if()abort_if(bool $boolean, mixed $code, string $message = '', array $headers = [])Conditionally throws an HTTP exception if boolean is true
abort_unless()abort_unless(bool $boolean, mixed $code, string $message = '', array $headers = [])Conditionally throws an HTTP exception if boolean is false

Sources: src/helpers.php41-97


Configuration and Caching

Configuration Access

The config() helper delegates to the Hypervel Config package for reading and writing configuration values.



















FunctionSignatureReturnsDescription
config()config(null|array|string $key = null, mixed $default = null)Repository|mixed|nullGets configuration value(s) or sets multiple values

Usage Patterns:

  • config() - Returns the entire configuration repository
  • config('app.name') - Returns a single configuration value
  • config('app.name', 'default') - Returns value with default fallback
  • config(['app.name' => 'MyApp']) - Sets configuration values

Sources: src/helpers.php274-287

Cache Access

FunctionSignatureReturnsDescription
cache()cache(null|array|string $key = null, mixed $default = null)CacheManager|mixed|boolGets/sets cache values or returns the cache manager

Usage Patterns:

  • cache() - Returns the CacheManager instance
  • cache('key') - Retrieves a value from cache
  • cache('key', 'default') - Retrieves with default fallback
  • cache(['key' => 'value'], 60) - Stores value for 60 minutes

Sources: src/helpers.php289-305


Authentication and Authorization

FunctionSignatureReturnsDescription
auth()auth(?string $guard = null)AuthFactoryContract&Guard|GuardReturns the authentication guard
policy()policy(object|string $class)mixedReturns the policy instance for the given class

The auth() helper delegates to \Hypervel\Auth\auth() and provides access to the authentication system. When called without arguments, it returns the default guard. When passed a guard name, it returns that specific guard.

Sources: src/helpers.php722-732 src/helpers.php497-508


Session and CSRF Protection

Session Management

FunctionSignatureReturnsDescription
session()session(array|string|null $key = null, mixed $default = null)SessionContract|mixedGets/sets session values or returns the session instance
csrf_token()csrf_token()?stringReturns the current CSRF token value
csrf_field()csrf_field()HtmlStringGenerates a hidden input field containing the CSRF token

The session() helper delegates to \Hypervel\Session\session() and supports three modes:

  • No arguments: Returns the SessionContract instance
  • String key: Returns session()->get($key, $default)
  • Array: Sets multiple session values via session()->put($key)

Sources: src/helpers.php636-648 src/helpers.php325-345

Cookie Management

FunctionSignatureReturnsDescription
cookie()cookie(?string $name = null, ...)CookieContract|CookieCreates a new cookie or returns the cookie manager

When called without arguments, returns the cookie manager. Otherwise, creates a new cookie with the specified parameters (name, value, minutes, path, domain, secure, httpOnly, raw, sameSite).

Sources: src/helpers.php307-323


Validation

FunctionSignatureReturnsDescription
validator()validator(array $data = [], array $rules = [], array $messages = [], array $customAttributes = [])ValidatorContractCreates a new validator instance

The validator helper resolves the ValidatorFactoryContract from the container and delegates to its make() method to create validator instances.

Sources: src/helpers.php662-678


Routing and URL Generation





































FunctionSignatureReturnsDescription
route()route(string $name, array $parameters = [], bool $absolute = true, string $server = 'http')stringGenerates URL to a named route
url()url(?string $path = null, array $extra = [], ?bool $secure = null)string|UrlGeneratorContractGenerates a URL for the application
secure_url()secure_url(string $path, array $extra = [])stringGenerates a secure (HTTPS) URL
asset()asset(string $path, ?bool $secure = null)stringGenerates a URL for an asset

All routing helpers delegate to corresponding functions in the \Hypervel\Router namespace.

Sources: src/helpers.php680-720


View Rendering

FunctionSignatureReturnsDescription
view()view(?string $view = null, array|Arrayable $data = [], array $mergeData = [])FactoryInterface|ViewInterfaceRenders a view or returns the view factory
method_field()method_field(string $method)HtmlStringGenerates a hidden input for HTTP method spoofing

The view() helper resolves the FactoryInterface from the container. When called without arguments, it returns the factory. When provided with a view name, it delegates to factory->make() to render the view.

Sources: src/helpers.php766-793


Translation

FunctionSignatureReturnsDescription
trans()trans(?string $key = null, array $replace = [], ?string $locale = null)TranslatorContract|array|stringTranslates the given message
trans_choice()trans_choice(string $key, $number, array $replace = [], ?string $locale = null)stringTranslates with pluralization
__()__(?string $key = null, array $replace = [], ?string $locale = null)TranslatorContract|array|stringShorthand alias for trans()

All translation helpers delegate to corresponding functions in the \Hypervel\Translation namespace.

Sources: src/helpers.php734-764


Event System and Broadcasting

























FunctionSignatureReturnsDescription
event()event(object $event)objectDispatches an event and returns it
broadcast()broadcast(mixed $event = null)PendingBroadcastBegins broadcasting an event

Sources: src/helpers.php407-421 src/helpers.php125-133


Job Dispatching

FunctionSignatureReturnsDescription
dispatch()dispatch(mixed $job)PendingClosureDispatch|PendingDispatchDispatches a job to its handler
dispatch_sync()dispatch_sync(mixed $job, mixed $handler = null)mixedDispatches a job synchronously

Both helpers delegate to the \Hypervel\Bus namespace. The dispatch() helper returns a PendingClosureDispatch if the job is a closure, otherwise returns a PendingDispatch instance.

Sources: src/helpers.php382-405


Logging and Debugging

Logging Helpers

FunctionSignatureReturnsDescription
logger()logger(?string $message = null, array $context = [])?LoggerInterfaceLogs a debug message or returns the logger
info()info(string|Stringable $message, array $context = [], bool $backtrace = false)voidLogs an info-level message with optional backtrace

The logger() helper resolves LoggerInterface from the container. When called without arguments, it returns the logger instance. When passed a message, it logs at the debug level and returns null.

The info() helper adds automatic backtrace information when the $backtrace parameter is true, appending the file and line number to the context.

Sources: src/helpers.php456-473 src/helpers.php441-454

Error Handling

FunctionSignatureReturnsDescription
report()report(string|Throwable $exception)voidReports an exception to the handler
rescue()rescue(callable $callback, $rescue = null, $report = true)mixedExecutes a callback and catches exceptions

The rescue() helper provides try-catch logic with automatic exception reporting. The $rescue parameter can be a value or a callback that receives the exception. The $report parameter controls whether exceptions are reported.

Sources: src/helpers.php596-634


Cryptography

FunctionSignatureReturnsDescription
bcrypt()bcrypt(string $value, array $options = [])stringHashes a value using bcrypt
encrypt()encrypt(mixed $value, bool $serialize = true)stringEncrypts a value
decrypt()decrypt(string $value, bool $unserialize = true)mixedDecrypts a value

The bcrypt() helper resolves the hash service from the container using the string alias 'hash' and delegates to its bcrypt driver. The encrypt() and decrypt() helpers resolve the 'encrypter' service.

Sources: src/helpers.php231-262


Date and Time

FunctionSignatureReturnsDescription
now()now(\DateTimeZone|string|null $tz = null)CarbonCreates a Carbon instance for the current time
today()today(\DateTimeZone|string|null $tz = null)CarbonCreates a Carbon instance for today's date

Both helpers directly create Carbon instances without container resolution, using Carbon::now() and Carbon::today() respectively.

Sources: src/helpers.php487-495 src/helpers.php650-660


Utility Helpers

Faker Instance

FunctionSignatureReturnsDescription
fake()fake(?string $locale = null)\Faker\GeneratorReturns a Faker instance for the specified locale

The fake() helper (available only when \Faker\Factory class exists) binds a Faker generator to the container using a locale-specific abstract key (Faker\Generator:{locale}). The locale defaults to app.faker_locale configuration or 'en_US'.

Sources: src/helpers.php423-439

Asset Versioning

FunctionSignatureReturnsDescription
mix()mix(string $path, string $manifestDirectory = '')HtmlString|stringReturns the path to a versioned Mix file

The mix() helper resolves the Mix service from the container and delegates all arguments to it for processing Laravel Mix manifests.

Sources: src/helpers.php475-485


Coroutine Helpers































FunctionSignatureReturnsDescription
go()go(callable $callable)bool|intExecutes a callable in a new coroutine
co()co(callable $callable)bool|intAlias for go()
defer()defer(callable $callable)voidDefers callable execution until coroutine exit

All coroutine helpers delegate to the \Hypervel\Coroutine namespace for managing Swoole coroutines.

Sources: src/helpers.php795-814


Helper Function Categories Summary

The following table provides a complete overview of all helper functions organized by functional category:

CategoryHelper FunctionsPrimary Service Dependency
Containerapp(), resolve()Application Container
Pathsbase_path(), app_path(), database_path(), storage_path(), config_path(), resource_path(), lang_path(), public_path()Application path methods
HTTP Requestrequest(), abort(), abort_if(), abort_unless()RequestContract, ExceptionHandler
HTTP Responseresponse(), redirect(), to_route()ResponseContract
Configurationconfig()Config Repository
Cachecache()Cache Manager
Authenticationauth(), policy()Auth Factory, Gate
Sessionsession(), csrf_token(), csrf_field()Session Contract
Cookiescookie()Cookie Contract
Validationvalidator()Validator Factory
Routingroute(), url(), secure_url(), asset()UrlGenerator
Viewsview(), method_field()View Factory
Translationtrans(), trans_choice(), __()Translator
Eventsevent(), broadcast()Event Dispatcher, Broadcast Factory
Jobsdispatch(), dispatch_sync()Bus Dispatcher
Logginglogger(), info()Logger Interface
Error Handlingreport(), rescue()Exception Handler
Cryptographybcrypt(), encrypt(), decrypt()Hash/Encrypter services
Date/Timenow(), today()Carbon (direct)
Utilitiesfake(), mix()Faker, Mix
Coroutinesgo(), co(), defer()Coroutine package

Sources: src/helpers.php1-815


Usage Patterns and Best Practices

When to Use Helpers vs Dependency Injection

Use helpers when:

  • Writing quick prototypes or simple controllers
  • Working in views, routes, or configuration files where DI is not available
  • Accessing frequently-used services with concise syntax (e.g., request(), auth())

Use dependency injection when:

  • Writing testable code that requires mocking
  • Building reusable, framework-agnostic components
  • Explicitly documenting service dependencies in class constructors

Container Availability

Most helpers check for container availability using ApplicationContext::hasContainer(). Path helpers provide fallback behavior using the BASE_PATH constant when the container is not yet initialized, which is useful during early bootstrap phases.


Delegation to Package-Specific Helpers

Several helpers delegate to package-specific helper functions rather than directly resolving services:

  • config()\Hypervel\Config\config()
  • cache()\Hypervel\Cache\cache()
  • route(), url(), secure_url(), asset()\Hypervel\Router\*
  • auth()\Hypervel\Auth\auth()
  • session(), csrf_token(), csrf_field()\Hypervel\Session\*
  • trans(), trans_choice(), __()\Hypervel\Translation\*
  • event()\Hypervel\Event\event()
  • dispatch(), dispatch_sync()\Hypervel\Bus\*
  • go(), co(), defer()\Hypervel\Coroutine\*

This pattern allows packages to maintain their own helper implementations while providing a unified interface through the Foundation helpers.

Sources: src/helpers.php99-112 src/helpers.php274-287 src/helpers.php680-814