Current SqueHub versionv2.0.0
Getting started · v2.x

Global helpers

SqueHub's global helpers are short entry points into existing Application services. They express common application intent; the Routing, View, Session, Auth, Database, and other subsystems still own the behavior. This guide describes the…

SqueHub's global helpers are short entry points into existing Application services. They express common application intent; the Routing, View, Session, Auth, Database, and other subsystems still own the behavior. This guide describes the functions defined in App/Core/Helper.php in SqueHub v2.0.0. It is the supported helper inventory, including the retained v1 compatibility functions.

Normal SqueHub HTTP and CLI bootstraps load that file with require_once. Composer's vendor/autoload.php alone does not load it. These are global functions, not methods of an App\Core\Helper class. In namespaced code, asset(...) works when there is no same-named local function; write \asset(...) when you need to identify the global one explicitly. Do not create a colliding project or Package global helper name.

Helpers that select an Application use the currently selected SqueHub context. Boot and select the intended Application before calling them in a CLI script or test. A helper call does not bootstrap another Application, load .env again, or open an unrelated connection. request() reads only the active HTTP request scope and fails outside it; it never creates a Request from $_SERVER. Controller injection remains the direct way to pass a Request to services.

Application and configuration

config(string $key, mixed $default = null): mixed reads a dot-separated key from the selected Application's configuration repository. It is read-only and returns the supplied default when the key is absent. Configuration is loaded at boot; this helper does not reopen .env or write configuration. See Configuration.

PHP
$name = config('app.name', 'SqueHub');

Routing and public asset URLs

route($name, $params = []) resolves a registered named route. Its modern registry result is a public path, including the selected Application's APP_BASE_PATH, not an absolute origin. Named path parameters are encoded and checked against the route pattern; optional trailing parameters may be omitted. Unknown names and missing or invalid required parameters fail rather than producing a guess. There is no helper argument for arbitrary query parameters. See Routing.

PHP
use App\Plugins\Route;
use App\Plugins\Request;

Route::path('/users/{user}')
    ->get(static fn (Request $request): string => (string) $request->route('user'))
    ->named('users.show');
Route::path('/dashboard')->get(static fn (): string => 'Dashboard')->named('dashboard');
Route::path('/reports/{year?}/{month?}')
    ->get(static fn (): string => 'Reports')
    ->named('reports.show');
$path = route('users.show', ['user' => 42]); // /users/42, or /app/users/42 under /app.

route('dashboard');                         // /dashboard, or /app/dashboard.
route('reports.show');                      // /reports.
route('reports.show', ['year' => 2026]);   // /reports/2026.

asset(string $url): string resolves an application-owned public asset URL for the selected Application. Use the same /assets/... reference in root and mounted deployments. It references images, CSS, JavaScript, fonts, media, documents, and other public files without inspecting their extensions. It does not check file existence, read filesystem paths, or serve the resource. Direct @style/@script resources and registered View assets use the same URL resolution internally; do not wrap those declarations in asset(). Host-bearing HTTP(S) and protocol-relative external URLs remain external; malformed hostless forms fail. See Public asset URLs for accepted local inputs, query/fragment behavior, external URLs, and validation boundaries.

PHP
<img src="{{ asset('/assets/images/logo.png') }}" alt="Logo">
<link rel="stylesheet" href="{{ asset('/assets/css/app.css') }}">
<script src="{{ asset('/assets/js/app.js') }}"></script>
<video src="{{ asset('/assets/media/intro.mp4') }}" controls></video>
<a href="{{ asset('/assets/files/manual.pdf') }}">Download manual</a>

With APP_BASE_PATH=/squehub-v2, the first call emits /squehub-v2/assets/images/logo.png. An already mounted input is not prefixed twice. Use route() for a named application route and asset() for a public resource; literal template attributes are not rewritten.

Responses and redirects

request(): Request returns the Request bound to the active HTTP handling scope. It throws LogicException outside that scope, including an ordinary CLI operation. It does not capture a new request and does not retain one from an earlier Kernel call. Pass the Request into a controller or middleware method when that dependency can be explicit. See HTTP requests.

PHP
$method = request()->method(); // Only while this Application handles a Request.

response() returns the established ResponseFactory; response($content, $status = 200, $headers = []) returns an ordinary Response. The factory provides json, redirect, binary, download, file, and stream creation. A download or inline file reads an application-selected local file when sent; passing the current Request to download or file opts into bounded single-file range handling. A stream producer runs at send time. See HTTP Responses.

PHP
return response('Saved', 201);
return response()->json(['saved' => true], 201);
return response()->redirect(route('users.show', ['user' => 42]));
return response()->download($authorizedPath, 'report.pdf');
return response()->stream(static fn (): iterable => ['first', 'second']);

redirect('/path', $status = 302) is the short form for a strict application-root path such as /dashboard. It returns an ordinary RedirectResponse without sending it. The selected Application's base path is applied once: under /app, redirect('/dashboard') sets a public /app/dashboard Location. The path cannot contain a query, fragment, percent escape, traversal segment, backslash, control character, or external/protocol-relative URL. Supply one of the supported redirect statuses (301, 302, 303, 307, or 308); withHeader() can add a validated header to the returned response. Its input is always interpreted as an application path: under /app, redirect('/app/foo') means the application's /app/foo route and becomes /app/app/foo. For a named route, route() has already produced a public mounted path, so use response()->redirect(route('dashboard')). Use response()->redirect($reviewedTarget) for an intentionally selected query-bearing or external destination after validating it in application code. See HTTP Responses and mounted HTTP paths.

redirectBack(Request $request, string $fallback = '/', int $status = 303): RedirectResponse reuses browser navigation's safe previous-path policy when the browser forms service is registered. Its first argument is an explicit Request with the selected Application's URL base path; a mismatched mount fails. It accepts a prior successful browser GET/HEAD path or a same-origin Referer inside the active mount, discards Referer query/fragment data, and otherwise uses the strict application-root fallback. Without browser navigation, it returns the fallback. The destination is mounted once. It does not trust raw HTTP_REFERER, and it is not a substitute for authorization on the destination. See Forms and HTTP requests.

PHP
return redirect('/dashboard');
return redirect('/dashboard', 303);
// For a reviewed raw Location plus additional headers, use the factory:
return response()->redirect('/dashboard', 303)->withHeader('X-Flow', 'profile');
return response()->redirect(route('users.show', ['user' => 42]));
return redirectBack($request, '/dashboard');

The zero-argument redirect() call retains the v1 compatibility object: its to() and back() methods immediately send a raw header and exit, and back() reads raw HTTP_REFERER. Do not use that form in new code. The old url(...$pathSegments) likewise constructs an absolute URL from raw server variables and is neither trusted-proxy-aware nor APP_BASE_PATH-aware. Use a named route() path, and choose a reviewed public origin separately for security-sensitive absolute links. See mounted HTTP paths.

Views, forms, and validation

csrf_token() returns the current Session-bound token value. csrf_field() returns the trusted hidden input markup with the configured field name. A .squehub.php form can use @csrf; when calling the HTML helper directly, emit its trusted markup raw. method_field($method) similarly returns a hidden _method field for PUT, PATCH, or DELETE; @method('PATCH') is the corresponding View directive. The forms guide covers browser method transport and CSRF enforcement.

PHP
<form method="post" action="{{ route('profile.update') }}">
    {!! csrf_field() !!}
    {!! method_field('PATCH') !!}
</form>
PHP
<form method="post" action="{{ route('profile.update') }}">
    @csrf
    @method('PATCH')
    <input name="email" value="{{ old('email', $email) }}">
    <input type="checkbox" name="news" {{ checked($wantsNews) }}>
    <option value="daily" {{ selected($frequency === 'daily') }}>Daily</option>
</form>

old($key = null, $default = null) reads filtered input flashed for the next request; errors() returns the read-only validation ErrorBag. checked() and selected() require a boolean and return only the fixed attribute name or an empty string. validator($data) starts standalone validation and returns a Validator; $request->validate(...) is the browser/API request path. See Validation and Forms.

PHP
$token = csrf_token();
$firstEmailError = errors()->first('email');
$result = validator(['email' => 'ada@example.com'])->check(['email' => 'required|email']);

json($value) encodes JSON with mandatory inline-script safety flags. In a View script body, use @json($value); in a quoted HTML attribute, use normal escaped {{ json($value) }}. classes($entries) composes text for a quoted class attribute and never marks it as trusted HTML. environment(...$names) and debugging() read the selected Application's environment and debug presentation state at render time. See Template Utilities.

PHP
<div class="{{ classes(['card', 'is-active' => $active]) }}"></div>
<script>window.pageData = @json($pageData);</script>
@if (environment('production') && !debugging())
    @script('/assets/js/app.min.js')
@endif

Session, identity, and data

session() returns the current Application's SessionStore; its get, put, flash, and pull methods retain their Session lifetimes. flash($key, $message = null) is the older message-specific bridge: with a message it writes the legacy _flash map, and without one it consumes that named message. Prefer the explicit Session API for new state and use the existing Notification View directives only for the legacy browser flash presentation. See Sessions.

auth() returns the selected Application's AuthManager. The helper takes no guard argument; use auth()->guard('admin') for a configured named guard. authorize() returns AuthorizationManager; allows() checks an ability and require() enforces it. Authentication and authorization are separate from View-only presentation directives. See Authentication and Authorization.

PHP
$user = auth()->user();
$admin = auth()->guard('admin')->user();
authorize()->require('reports.view');
session()->flash('notice', 'Saved');

database() returns the Application's DatabaseManager, db($table) starts a query on its default connection, and schema($connection = null) returns the default or named connection's Schema service. Connection objects are built lazily; actual database operations still require the configured backend. See Database and Schema.

PHP
$users = db('users')->filter('active', 1)->all();
$reporting = database()->table('reports', 'reporting');
$schema = schema('reporting');

Service gateways

The following helpers return Application-owned managers or stores. They are concise alternatives to the corresponding App\Plugins gateway; each subsystem guide owns the full API and configuration contract. Merely resolving an optional service does not require unrelated Redis, Mail, or database infrastructure.

ConcernGlobal helperTypical use and boundary
Account securityaccountSecurity()accountSecurity()->forGuard('web'); reset and verification policy stays in the manager.
Cryptographycrypto()crypto()->encrypt($plaintext); key configuration remains mandatory for use.
Healthhealth()health()->ready(); readiness can check configured dependencies.
Rate limitingrateLimiter()rateLimiter()->consume('login', $key, 5, 60); configured stores govern enforcement.
Mailmailer()mailer()->send($message); delivery needs a valid transport and MailMessage.
Notificationsnotifications()notifications()->send($recipient, $notification); delivery is distinct from browser flash messages.
Queuequeue()queue()->dispatch($job) uses the default connection; pass its fourth argument for a named connection.
Redisredis()redis()->connection('default'); Redis is optional and connection is lazy.
Lockslock()lock()->acquire('invoice:123', ttl: 30) uses the selected Application's configured lease store.
Schedulerschedule()schedule()->call($callback) registers an Application schedule definition.
Logginglogger()logger()->info('Task finished'); do not log secrets.
Cachecache()cache()->read('key') or cache()->store('key', $value); uses configured store.
Storagestorage()storage()->write('reports/latest.txt', $content); drive($name) selects a named drive.
Eventsevents()events()->listen(Event::class, $listener) and events()->emit($event).
Diagnosticsdiagnostics()diagnostics()->requestId() returns the active request ID, or null outside one.
Outgoing HTTPhttpClient()httpClient()->get($url) uses the configured outgoing client and its safety policy.
OIDCoauth()oauth()->provider('company') selects a configured external identity provider.
Webhookswebhooks()webhooks()->endpoint('payments') selects a configured outgoing peer; inbound sources use source($name).

SqueHub keeps this helper list small. Remember-me uses the existing auth()/App\Plugins\Auth surface. The optional RBAC, MFA, and signed URL features have App\Plugins gateways and Application-owned services; they do not introduce rbac(), mfa(), or signed_url() global helpers.

Complete reference

All entries below are global declarations in App/Core/Helper.php. “Application” means a selected SqueHub Application; “Session” means an active or startable Session store; “HTTP” means a current browser/request context when the operation uses it. The examples and links above give the normal usage; this table records exact helper signatures and return contracts. A helper that returns a manager can be called from CLI after Application boot, although the manager's own operation may still require configured infrastructure.

Helper and signatureReturns / purposeContextStatus
config(string $key, mixed $default = null): mixedRead-only configuration value or defaultApplicationSupported
session(): SessionStoreApplication Session storeApplication; Session on useSupported
auth(): AuthManagerAuthentication manager; named guard via guard()Application; request identity on useSupported
authorize(): AuthorizationManagerAbility checks and enforcementApplication; policy context on useSupported
accountSecurity(): AccountSecurityManagerCredential/reset/verification serviceApplication; policy context on useSupported
crypto(): CryptManagerEncryption/signing managerApplication; configured key for useSupported
health(): HealthManagerLiveness/readiness checksApplicationSupported
rateLimiter(): RateLimiterNamed rate-limit policiesApplication; store on useSupported
mailer(): MailerOutgoing mail serviceApplication; transport on sendSupported
notifications(): NotificationManagerDelivery notificationsApplication; channel on sendSupported
queue(): QueueManagerQueue dispatch/worker gatewayApplication; selected connection on useSupported
redis(): RedisManagerOptional named Redis connectionsApplication; Redis on connectSupported
lock(): LockManagerConfigured named lease acquisitionApplication; selected store on useSupported
schedule(): SchedulerScheduled task definitionsApplicationSupported
old(?string $key = null, mixed $default = null): mixedFlashed old inputApplication; Session/request lifecycleSupported
route($name, $params = [])Named public route pathActive route registry or legacy routerSupported
asset(string $url): stringPublic asset URLApplicationSupported
csrf_token(): stringSession-bound CSRF tokenApplication; SessionSupported
csrf_field(): stringTrusted hidden-input HTMLApplication; SessionSupported
method_field(mixed $method): stringTrusted _method HTML for PUT/PATCH/DELETENone beyond helper bootstrapSupported
checked(mixed $condition): stringFixed checked or empty textBoolean argumentSupported
selected(mixed $condition): stringFixed selected or empty textBoolean argumentSupported
json(mixed $value): stringInline-script-safe JSON textEncodable valueSupported
classes(array $entries): stringClass attribute textValid class entriesSupported
environment(string ...$names): boolEnvironment-name matchApplication; at least one nameSupported
debugging(): boolEffective debug flagApplicationSupported
errors(): ErrorBagRead-only validation errorsApplication; Session/request lifecycleSupported
request(): RequestCurrent bound HTTP RequestActive HTTP scope; throws outside itSupported
`response(?string $content = null, int $status = 200, array $headers = []): ResponseResponseFactory`Response with arguments; factory with noneHelper bootstrapSupported
redirect(?string $path = null, int $status = 302): objectSupplied strict application path returns RedirectResponse; zero arguments return legacy immediate redirect objectApplication for path form; legacy HTTP globals for zero-argument formSupported path form; compatibility-only zero-argument form
redirectBack(Request $request, string $fallback = '/', int $status = 303): RedirectResponseSafe browser previous path or strict local fallbackApplication and explicit RequestSupported
database(): DatabaseManagerNamed/default database gatewayApplication; backend on querySupported
db(string $table): QueryBuilderDefault-connection table queryApplication; backend on executionSupported
schema(?string $connection = null): SchemaDefault or named SchemaApplication; backend on operationSupported
validator(array $data): ValidatorStandalone validationInput dataSupported
logger(): LoggerConfigured loggingApplicationSupported
cache(): CacheStoreConfigured Cache storeApplication; selected backend on useSupported
storage(): StorageManagerDefault/named Storage drivesApplication; selected drive on useSupported
events(): EventDispatcherListener registration and emissionApplicationSupported
diagnostics(): DiagnosticsCurrent operational counters/request IDApplication; HTTP data during requestSupported
httpClient(): HttpClientConfigured outgoing HTTP clientApplication; network on sendSupported
oauth(): OAuthManagerConfigured OIDC providersApplication; provider on useSupported
webhooks(): WebhookManagerConfigured incoming/outgoing peersApplication; peer on useSupported

v1 compatibility and migration

These functions still exist in App/Core/Helper.php for older application code. Their presence does not make their old behavior a recommended v2 pattern. The upgrade guide gives migration order.

Helper and signatureCurrent behaviorV2 direction
startSessionIfNotStarted()Starts the Application Session store.Use session() and let its operations start the store.
validateCsrfToken(): voidLegacy POST-only check; throws the modern CSRF exception on denial.Let Kernel CSRF middleware protect browser routes; use @csrf/csrf_field() in forms.
CsrfTokenValidator(): boolLegacy POST-only boolean check of _csrf/_token in globals.Use Kernel CSRF protection and current Request handling.
is_post(): boolReads raw $_SERVER['REQUEST_METHOD']; returns false when no request method exists in CLI.Use injected $request->method() === 'POST'.
maskEmail(string $email): stringMasks all but first two local-part characters.Application-specific presentation utility; validate input first.
maskPhoneNumber(string $phone): stringMasks all but the last two characters.Application-specific presentation utility; validate input first.
slugify(string $text): stringLegacy transliteration and slug conversion.Keep only where existing output is required; evaluate a project utility for new slug policy.
flash(string $key, ?string $message = null)Writes/consumes the legacy _flash message map.Use session()->flash() for new Session flash data.
priceFormatter(float $amount, string $currency = '', bool $symbolBefore = true, int $decimals = 2): stringNumber formatting with optional currency text.Application-specific currency/locale presentation.
url(...$pathSegments)Absolute URL from raw server protocol/Host.Use route() for named public paths and a reviewed origin for absolute links.
redirect() with no argumentto()/back() immediately send header and exit; back() trusts raw Referer.Use redirect('/path') for a local application path, response()->redirect(route('name')) for a named route, or redirectBack($request, '/fallback') for safe browser back behavior.

The published v1 helper page also described project and Package Utils files as globally loaded. V2's root legacy Bootstrap.php eagerly requires PHP files under the first matching Project/Utils casing variant during normal application startup. Package utility files load only for enabled Packages through their activation lifecycle; a disabled Package does not contribute helpers. Composer autoload alone does not run either loader. Prefer namespaced utility classes where possible, and avoid SqueHub/PHP global function name collisions.