Helper Functions

ZephyrPHP provides a collection of global helper functions to make common tasks more convenient. These helpers follow industry-standard naming conventions found in Laravel and other modern frameworks.

Application Helpers

app()

Get the application instance or resolve a service from the container:

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

// Resolve a service from the container
$logger = app('logger');
$mailer = app(Mailer::class);

// With parameters
$service = app(MyService::class, ['config' => $config]);

container()

Get the container instance:

$container = container();
$container->bind('service', MyService::class);

resolve()

Resolve a service from the container:

$service = resolve(UserService::class);
$mailer = resolve('mailer', ['debug' => true]);

singleton()

Register a singleton in the container:

singleton('cache', CacheService::class);
singleton(PaymentGateway::class, StripeGateway::class);

bind()

Bind a service to the container:

bind('logger', FileLogger::class);
bind(LoggerInterface::class, DatabaseLogger::class);

tagged()

Get all services with a specific tag:

$validators = tagged('validators');
$handlers = tagged('event.handlers');

Request Helpers

request()

Get the request instance or a specific input value:

// Get the request instance
$request = request();

// Get a specific input value
$name = request('name');

// With default value
$page = request('page', 1);

// Access request methods
$email = request()->string('email');
$age = request()->integer('age');
$remember = request()->boolean('remember');

old()

Retrieve old input from the previous request (for form repopulation):

$email = old('email');
$name = old('name', 'Default Name');

Response Helpers

response()

Create a new response:

// Simple response
return response('Hello World');

// With status code
return response('Not Found', 404);

// With headers
return response('Hello', 200, ['X-Custom' => 'Value']);

json()

Create a JSON response:

return json(['name' => 'John', 'email' => 'john@example.com']);
return json(['error' => 'Not found'], 404);

redirect()

Create a redirect response:

redirect('/dashboard');
redirect('/login', 301);

back()

Redirect back to the previous page:

back();
back('/fallback-url'); // With fallback if no previous URL

abort()

Throw an HTTP exception:

abort(404);
abort(404, 'User not found');
abort(403, 'Access denied');

abort_if()

Throw an HTTP exception if condition is true:

abort_if(!$user->isAdmin(), 403, 'Access denied');
abort_if($post->isDeleted(), 404, 'Post not found');

abort_unless()

Throw an HTTP exception unless condition is true:

abort_unless($user->canEdit($post), 403, 'Cannot edit this post');
abort_unless($request->has('token'), 400, 'Token required');

Session Helpers

session()

Access session data:

// Get the session instance
$session = session();

// Get a value
$userId = session('user_id');

// With default
$theme = session('theme', 'light');

flash()

Get or set flash data:

// Set flash data
flash('success', 'Your changes have been saved!');

// Get flash data
$message = flash('success');

csrf_token()

Get the current CSRF token:

$token = csrf_token();

csrf_field()

Generate a CSRF hidden input field:

echo csrf_field();
// <input type="hidden" name="_token" value="...">

csrf_meta()

Generate a CSRF meta tag (useful for AJAX):

echo csrf_meta();
// <meta name="csrf-token" content="...">

method_field()

Generate a hidden method field for PUT/PATCH/DELETE forms:

echo method_field('PUT');
// <input type="hidden" name="_method" value="PUT">

echo method_field('DELETE');
// <input type="hidden" name="_method" value="DELETE">

Path Helpers

base_path()

Get the application base path:

$basePath = base_path();
$configPath = base_path('config/app.php');

storage_path()

Get the storage directory path:

$storagePath = storage_path();
$logPath = storage_path('logs/app.log');

public_path()

Get the public directory path:

$publicPath = public_path();
$imagePath = public_path('images/logo.png');

URL Helpers

url()

Generate a full URL:

$url = url('/users');
$url = url('/users/1/edit');

get_base_url()

Get the application base URL:

$baseUrl = get_base_url();
// Returns: 'https://example.com'

route()

Generate a URL for a named route:

$url = route('home');
$url = route('users.show', ['id' => 1]);
$url = route('posts.edit', ['post' => 5]);

Asset Helpers

These helpers use the powerful Asset Manager which supports versioning, CDN, and more. See the Asset Management documentation for full details.

asset()

Generate a versioned URL for an asset:

$cssUrl = asset('assets/css/styles.css');
// Returns: /assets/css/styles.css?v=1737741234

$jsUrl = asset('assets/js/app.js');

// With options (disable CDN, custom version)
$url = asset('assets/css/app.css', ['cdn' => false, 'version' => '2.0.0']);

css()

Generate a CSS link tag with automatic versioning:

echo css('assets/css/styles.css');
// <link rel="stylesheet" href="/assets/css/styles.css?v=1737741234">

echo css('assets/css/print.css', ['media' => 'print']);
// <link rel="stylesheet" href="/assets/css/print.css?v=..." media="print">

js()

Generate a JavaScript script tag:

echo js('assets/js/app.js');
// <script src="/assets/js/app.js?v=..."></script>

echo js('assets/js/app.js', ['defer' => true]);
// <script src="/assets/js/app.js?v=..." defer></script>

echo js('assets/js/module.js', ['type' => 'module', 'async' => true]);
// <script src="/assets/js/module.js?v=..." type="module" async></script>

image()

Generate an image tag with automatic lazy loading:

echo image('assets/images/logo.png', 'Logo');
// <img src="/assets/images/logo.png?v=..." alt="Logo" loading="lazy">

echo image('assets/images/hero.jpg', 'Hero', ['loading' => 'eager', 'fetchpriority' => 'high']);
// <img src="/assets/images/hero.jpg?v=..." alt="Hero" loading="eager" fetchpriority="high">

View Helper

view()

Render a view template:

return view('home');
return view('users/profile', ['user' => $user]);
return view('emails/welcome', ['name' => $name]);

Configuration Helpers

config()

Get configuration values:

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

// With default
$debug = config('app.debug', false);

// Nested values
$dbHost = config('database.connections.mysql.host');

env()

Get environment variables:

$debug = env('APP_DEBUG');
$dbHost = env('DB_HOST', '127.0.0.1');

// Automatic type casting
$debug = env('APP_DEBUG');    // Returns boolean true/false
$port = env('DB_PORT');       // Returns string value

The env() function automatically converts special string values:

  • 'true', '(true)'true
  • 'false', '(false)'false
  • 'null', '(null)'null
  • 'empty', '(empty)'''

Logging Helper

logger()

Get the logger instance:

// Get the default logger
$logger = logger();
$logger->info('User logged in', ['user_id' => 1]);

// Get a specific channel
$logger = logger('slack');
$logger->error('Critical error occurred');

Debugging Helpers

dd()

Dump and die - useful for debugging:

dd($user);
dd($request->all(), $errors);

dump()

Dump without dying:

dump($data);
dump($user, $roles);

Date Helper

now()

Get current DateTime:

$now = now();
// Returns DateTime instance

echo $now->format('Y-m-d H:i:s');

String Helpers

e()

HTML escape a string:

$safe = e($userInput);
// Converts <script> to &lt;script&gt;

class_basename()

Get the class name without namespace:

$name = class_basename('App\\Models\\User');
// Returns: 'User'

$name = class_basename($userObject);
// Returns: 'User'

Value Helpers

value()

Return the value or call a closure:

$result = value('default');
// Returns: 'default'

$result = value(fn() => expensive_computation());
// Returns result of closure

filled()

Check if a value is "filled" (not blank):

filled('hello');     // true
filled('');          // false
filled('   ');       // false
filled([1, 2]);      // true
filled([]);          // false
filled(null);        // false

blank()

Check if a value is "blank" (empty):

blank('');           // true
blank('   ');        // true
blank(null);         // true
blank([]);           // true
blank('hello');      // false

tap()

Call a callback with a value and return the value:

$user = tap(User::find(1), function($user) {
    $user->updateLastLogin();
});
// Returns the user after calling updateLastLogin()

retry()

Retry a callback multiple times:

$result = retry(3, function($attempt) {
    return file_get_contents('https://api.example.com/data');
}, 100); // 100ms delay between retries

Collection Helper

collect()

Returns the array as-is (placeholder for future Collection class):

$items = collect([1, 2, 3, 4, 5]);
// Currently returns the array directly

Usage in Templates

Many helpers are available in Twig templates:

{# Asset URLs #}
<link rel="stylesheet" href="{{ asset('css/styles.css') }}">
{{ css('css/app.css')|raw }}
{{ js('js/app.js')|raw }}

{# Route URLs #}
<a href="{{ route('users.show', {id: user.id}) }}">View</a>

{# Session data #}
{{ session('user_name') }}

{# CSRF protection #}
<form method="POST">
    {{ csrf_field()|raw }}
    {{ method_field('PUT')|raw }}
    ...
</form>

{# Old input for form repopulation #}
<input type="email" name="email" value="{{ old('email') }}">

{# Config values #}
{{ config('app.name') }}

{# Flash messages #}
{% if flash('success') %}
    <div class="alert alert-success">{{ flash('success') }}</div>
{% endif %}

Controller Shortcuts

Inside controllers, you can use convenient shortcuts instead of accessing $this->request:

class UserController extends Controller
{
    public function store()
    {
        // Input shortcuts
        $name = $this->string('name');
        $age = $this->integer('age');
        $active = $this->boolean('active');
        $tags = $this->array('tags');

        // Check input
        if ($this->filled('email')) {
            $email = $this->input('email');
        }

        // Get specific keys
        $data = $this->only(['name', 'email', 'password']);

        // Validation
        $validated = $this->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email'
        ]);

        // Response shortcuts
        return $this->json(['success' => true]);
    }
}

Helper Function Reference

Category Function Description
Applicationapp()Get app instance or resolve service
Applicationcontainer()Get container instance
Applicationresolve()Resolve service from container
Applicationsingleton()Register singleton
Applicationbind()Bind service to container
Requestrequest()Get request or input value
Requestold()Get old input value
Responseresponse()Create response
Responsejson()Create JSON response
Responseredirect()Redirect to URL
Responseback()Redirect back
Responseabort()Throw HTTP exception
Sessionsession()Get session or value
Sessionflash()Get/set flash data
Securitycsrf_token()Get CSRF token
Securitycsrf_field()Generate CSRF input
Securitycsrf_meta()Generate CSRF meta tag
Securitymethod_field()Generate method input
Pathbase_path()Get base path
Pathstorage_path()Get storage path
Pathpublic_path()Get public path
URLurl()Generate URL
URLroute()Generate route URL
URLasset()Generate asset URL
Assetcss()Generate CSS link tag
Assetjs()Generate JS script tag
Assetimage()Generate image tag
Viewview()Render template
Configconfig()Get config value
Configenv()Get environment variable
Logginglogger()Get logger instance
Debugdd()Dump and die
Debugdump()Dump variables
Datenow()Get current DateTime
Stringe()HTML escape
Stringclass_basename()Get class name
Valuevalue()Get value or call closure
Valuefilled()Check if filled
Valueblank()Check if blank
Valuetap()Tap and return
Valueretry()Retry with callback