Skip to Content
ModulesHelpers

Helpers Reference

Flute CMS provides many helper functions that simplify module development. These functions are available globally and can be used in controllers, templates, and services.

Main categories of helpers:

  • Service Container and DI
  • Database and ORM
  • HTTP Requests and Responses
  • Templates and Views
  • Authentication and Authorization
  • Localization and Translations
  • Caching and Performance
  • Filesystem and Assets
  • Events and Logging

Quick Reference

FunctionDescriptionUsage Example
rep()Get ORM repositoryrep(User::class)->findByPK(1)
transaction()Create DB transactiontransaction($entity)->run()
request()Current HTTP requestrequest()->get('page', 1)
response()Create HTTP responseresponse()->json($data)
user()Current useruser()->can('permission')
template()Template systemtemplate()->render('view', $data)
route()Generate route URLroute('blog.show', ['id' => 1])
url()Generate URLurl('/path/to/resource')
active()/is_active()Active route (classes/check)active('admin.*', 'active')
__()Translate string__('blog.welcome')
translation()Translation servicetranslation()->setLocale('ru')
cache()Caching systemcache()->get('key', 'default')
config()Configurationconfig('app.name')
events()Event systemevents()->dispatch($event)
logs()Logginglogs()->info('message')
session()Work with sessionsession()->set('key', 'value')
cookie()Work with cookiescookie()->set('name', 'value')
email()Mailemail()->to('user@test')->subject('Hi')->send()
encrypt()Encryptionencrypt()->encryptString('data')

Service Container

app()

Get instances of services from DI container.

<?php // Get service $logger = app(\Flute\Core\Services\LoggerService::class); // Bind service app()->bind('my.service', function() { return new MyService(); }); // Get bound service $service = app('my.service');

Configuration

config()

Work with configuration files.

<?php // Get value $perPage = config('blog.articles_per_page', 10); // Get entire config $blogConfig = config('blog'); // Set value (at runtime) config(['blog.enabled' => false]);

Events

events()

Work with event system.

<?php // Register listener events()->addDeferredListener('user.registered', function($event) { // Handle event }); // Dispatch event events()->dispatch(new UserRegisteredEvent($user));

Logging

logs()

Write logs to system.

<?php // Main log logs()->info('User logged in', ['user_id' => $user->id]); // Specific channel logs('security')->warning('Suspicious activity detected', [ 'ip' => request()->getClientIp(), 'user_agent' => request()->headers->get('User-Agent') ]); // Log errors logs('errors')->error('Database connection failed', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString() ]);

Filesystem

fs()

Work with files and directories.

<?php // Check file existence if (fs()->exists('uploads/image.jpg')) { // File exists } // Read file $content = fs()->read('config/app.php'); // Write file fs()->write('logs/custom.log', 'Log message'); // Create directory fs()->makeDirectory('uploads/thumbnails'); // Copy file fs()->copy('source.jpg', 'destination.jpg'); // Delete file fs()->delete('temp/file.tmp');

finder()

Symfony Finder for searching files.

<?php // Search PHP files $files = finder() ->files() ->name('*.php') ->in('app/Modules') ->getIterator(); // Search by depth $controllers = finder() ->files() ->name('*Controller.php') ->in('app/Modules') ->depth('== 2') ->getIterator();

HTTP Requests and Responses

request()

Work with current HTTP request.

<?php // Get parameters $page = request()->get('page', 1); $search = request()->query->get('search'); // Get request body $data = request()->request->all(); // Headers $userAgent = request()->headers->get('User-Agent'); $contentType = request()->headers->get('Content-Type'); // Files $uploadedFile = request()->files->get('image'); // Route attributes $id = request()->getAttribute('id'); // Check method if (request()->isMethod('POST')) { // POST request } // Check content type if (request()->expectsJson()) { // Expects JSON response } // HTMX helpers request()->htmx()->isHtmxRequest(); request()->htmx()->isBoosted();

response()

Create HTTP responses.

<?php // JSON response return response()->json(['data' => $articles]); // View return response()->view('blog::index', compact('articles')); // Redirect return response()->redirect('/dashboard'); // Error return response()->error(404, 'Page not found'); // Download file return response()->download('file.pdf');

json()

Create JSON responses.

<?php // Simple JSON return json(['message' => 'Success']); // With data and status return json(['data' => $user], 201); // With headers return json(['token' => $token], 200, ['Authorization' => 'Bearer ' . $token]);

redirect()

Create redirects.

<?php // Simple redirect return redirect('/dashboard'); // Redirect to route return redirect(route('user.profile', ['id' => $user->id])); // Redirect with flash message return redirect('/login')->with('error', 'Invalid credentials');

Templates

template()

Work with template system.

<?php // Render template $content = template()->render('blog::article', ['article' => $article]); // Add global variable template()->addGlobal('site_name', 'My Blog'); // Register component template()->registerComponent('alert', AlertComponent::class); // Add script template()->addScript('/js/custom.js'); // Add style template()->addStyle('/css/custom.css'); // Get Blade and Yoyo $blade = template()->getBlade(); $yoyo = template()->getYoyo(); // automatically has route /live or /admin/live

view() and render()

Rendering views.

<?php // Render with data $content = render('blog::index', ['articles' => $articles]); // Get View object $view = view('blog::index', ['articles' => $articles]);

Routing

router()

Work with routes.

<?php // Get current route $currentRoute = router()->getCurrentRoute(); // Generate URL $url = router()->url('blog.articles.show', ['id' => 1]); // Check route existence if (router()->hasRoute('blog.articles.show')) { // Route exists }

route()

Generate route URLs.

<?php // Simple generation $url = route('blog.articles.index'); // With parameters $url = route('blog.articles.show', ['id' => $article->id]); // With additional parameters $url = route('blog.search', ['q' => 'php', 'page' => 1]);

Active Routes

<?php // Get active router $activeRouter = active_router(); // Check active route if (is_active('blog.articles.*')) { // We are on blog articles page } // CSS class for active menu item $class = active('blog.articles.index', 'active');

Database and ORM

dbal() and db()

Low-level database work via Cycle Database (DBAL).

<?php // Connection manager $manager = dbal(); // \Cycle\Database\DatabaseManager // Active DB (default) or named $db = db(); // default $analytics = db('analytics'); // Examples: SELECT COUNT(*) $exists = db()->select()->from('users')->where('email', $email)->count() > 0; // Delete all rows from table db()->delete('logs')->run(); // Note: for most cases ORM (ActiveRecord) is preferred

orm()

Work with ORM.

<?php // Get ORM $orm = orm(); // ORM Transaction $article = new Article(); $article->title = 'Hello'; transaction($article)->run(); // Database of ORM source entity // Allows getting connection to which entity is bound in ORM schema $entityDb = ormdb(\Flute\Core\Database\Entities\User::class);

rep()

Get entity repository (RepositoryInterface).

<?php // User repository $userRepository = rep(\Flute\Modules\User\Database\Entities\User::class); // Find by ID $user = $userRepository->findByPK(1); // Find by conditions (via Select) $activeUsers = $userRepository->select() ->where('active', true) ->fetchAll(); // ActiveRecord API (recommended way) $user = \Flute\Core\Database\Entities\User::findByPK(1); $users = \Flute\Core\Database\Entities\User::findAll(['active' => true]);

It is recommended to use ActiveRecord API: User::findByPK(1), User::query()->where(...)->fetchAll().

transaction()

Manage ORM transactions (EntityManager).

<?php // Save/delete multiple entities in one command $em = transaction([$article, $comment], 'persist'); $em->run(); // Supported operations: 'persist', 'persistState', 'delete', 'clean', as well as chain methods on EntityManager transaction($entity, 'delete')->run();

Authentication and Authorization

user()

Work with current user.

<?php // Current user $currentUser = user(); // Check authentication if (user()->isLoggedIn()) { $userId = user()->id; $userName = user()->name; } // Check permissions if (user()->can('manage_articles')) { // User can manage articles } // Check role if (user()->hasRole('admin')) { // User is admin } // Special checks user()->isLoggedIn(); user()->isGuest();

Localization

__()

Translate strings.

<?php // Simple translation $message = __('blog.welcome'); // With parameters $message = __('blog.articles_count', ['count' => $count]); // With pluralization $message = __('blog.comment_count', ['count' => $count]);

translation()

Work with translation service.

<?php // Set locale translation()->setLocale('ru'); // Get current locale $currentLocale = translation()->getLocale(); // Add translations translation()->addTranslations([ 'custom.message' => 'Custom message' ]); // Clear catalog cache (in performance mode) translation()->flushLocaleCache('ru');

UI Components (Blade)

Short example of using UI components. Full overview — in the “Components and Usage” section.

<x-card class="my-3"> <x-forms.field class="mb-3"> <x-forms.label for="title" required>@t('def.title'):</x-forms.label> <x-input name="title" id="title" :value="old('title')" /> </x-forms.field> <button class="btn btn-primary">@t('def.save')</button> </x-card>

Caching

cache()

Work with cache.

<?php // Save to cache cache()->set('user_profile_' . $userId, $profile, 3600); // Get from cache $profile = cache()->get('user_profile_' . $userId); // Check existence if (cache()->has('user_profile_' . $userId)) { // Data is in cache } // Delete from cache cache()->delete('user_profile_' . $userId); // Clear entire cache cache()->clear(); // Callback caching $user = cache()->callback('user_' . $userId, function() use ($userId) { return rep(User::class)->findByPK($userId); }, 3600); // Temporary caching and manual clearing (used in events()->addDeferredListener) cache()->getKeys('flute.deferred_listeners*');

Payments

payments()

Work with payment system.

<?php // Get all gateways $gateways = payments()->getAllGateways(); // Get specific gateway $stripeGateway = payments()->getGateway('stripe'); // Create payment $result = payments()->processor()->processPayment($paymentData);

Validation

validator()

Validate data.

<?php // Create validator $validator = validator(); // Validate data $validated = $validator->validate($input, [ 'title' => 'required|string|min-str-len:3|max-str-len:255', 'email' => 'required|email', 'age' => 'nullable|integer|min:18|max:100' ]); if (!$validated) { $errors = $validator->getErrors(); // Handle errors }

Flash Messages

flash()

Work with flash messages.

<?php // Set message flash()->add('success', 'Article created successfully'); // Different message types flash()->add('error', 'An error occurred'); flash()->add('warning', 'Warning'); flash()->add('info', 'Information');

toast()

Toast notifications.

<?php // Success notification toast()->success('Data saved')->push(); // Error toast()->error('Failed to save')->push(); // With custom title toast()->warning('Attention!') ->message('Session expiring') ->push();

URL Utilities

url()

Generate URL.

<?php // Absolute URL $fullUrl = url('/blog/articles'); // Asset URL $assetUrl = url('css/app.css'); // With protocol $secureUrl = url('/admin', true); // https

Date Utilities

now()

Work with dates.

<?php // Current date and time $now = now(); // DateTime // Date manipulations $tomorrow = now()->modify('+1 day'); $lastWeek = now()->modify('-1 week');

Encryption

encrypt()

Encrypt data.

<?php // Encrypt string $encrypted = encrypt()->encryptString('secret data'); // Decrypt $decrypted = encrypt()->decryptString($encrypted);

Sessions

session()

Work with sessions.

<?php // Set value session()->set('user_id', $userId); // Get value $userId = session()->get('user_id'); // Check existence if (session()->has('cart')) { $cart = session()->get('cart'); } // Remove session()->remove('temp_data'); // Clear session session()->clear();

Cookies

Work with cookies.

<?php // Set cookie cookie()->set('theme', 'dark', 86400); // 24 hours // Get cookie $theme = cookie()->get('theme', 'light'); // Check existence if (cookie()->has('preferences')) { $prefs = cookie()->get('preferences'); } // Delete cookie cookie()->delete('temp_token');

Email

email()

Send email messages.

<?php // Send simple message email()->to('[email protected]') ->subject('Welcome') ->body('Welcome to our site!') ->send(); // HTML message email()->to('[email protected]') ->subject('New Order') ->html('<h1>Your order received</h1><p>Order number: #123</p>') ->send(); // With attachments email()->to('[email protected]') ->subject('Report') ->body('Your monthly report') ->attach('/path/to/report.pdf') ->send();