adrianbaez/short-code-bundle
Laravel bundle that adds shortcode parsing to your app, letting you register custom shortcodes and render dynamic content inside text/HTML. Useful for CMS-style pages, editors, emails, and user-generated content needing embedded components.
Installation Add the package via Composer:
composer require adrianbaez/short-code-bundle
Register the bundle in config/app.php under providers:
Adrianbaez\ShortCodeBundle\ShortCodeServiceProvider::class,
Publish the config (if needed):
php artisan vendor:publish --provider="Adrianbaez\ShortCodeBundle\ShortCodeServiceProvider"
Basic Usage
The package provides a ShortCode facade to decode strings. Example:
use Adrianbaez\ShortCodeBundle\Facades\ShortCode;
$encoded = ShortCode::encode('Hello {name}!');
$decoded = ShortCode::decode($encoded, ['name' => 'World']);
// Output: "Hello World!"
First Use Case Replace hardcoded strings in emails, notifications, or templates with dynamic placeholders:
$template = ShortCode::decode(
'Welcome {user}, your code is {verification_code}',
['user' => 'John', 'verification_code' => 'ABC123']
);
Dynamic Email Templates Store templates in the database with placeholders, then decode on-the-fly:
$emailTemplate = DB::table('email_templates')->where('key', 'welcome')->first()->body;
$renderedEmail = ShortCode::decode($emailTemplate, $userData);
API Response Wrapping Standardize API responses with consistent placeholders:
$response = [
'message' => ShortCode::decode('Data fetched for {user}', ['user' => $request->user()->name]),
'data' => $data,
];
Localization with Placeholders Combine with Laravel’s localization:
$greeting = __('welcome.message', ['name' => ShortCode::decode('{user.name}', $user)]);
Cache Decoded Strings Cache frequently used decoded strings to avoid repeated parsing:
$cached = Cache::remember("shortcode_{$key}", now()->addHours(1), function () use ($key, $data) {
return ShortCode::decode($key, $data);
});
Validation Validate encoded strings before decoding to catch malformed placeholders:
if (!ShortCode::isValid($encodedString)) {
throw new \InvalidArgumentException('Invalid short code format.');
}
Custom Placeholder Syntax
Extend the bundle by overriding the ShortCode class to support custom delimiters (e.g., {{name}}):
ShortCode::setDelimiters('{{', '}}');
Deprecated Package
str_replace or template engine logic.No Built-in Security
$safeData = array_map('htmlspecialchars', $userInput);
ShortCode::decode($template, $safeData);
Nested Placeholders
The package does not support nested placeholders (e.g., {user.{profile.name}}). Flatten data manually:
$data = ['user' => ['profile' => ['name' => 'Alice']]];
ShortCode::decode('{user.profile.name}', $data); // Fails; pre-process data.
Config Overrides The package lacks a published config file. Hardcode delimiters or logic in the service provider if needed:
// In ShortCodeServiceProvider.php
$this->app->singleton('shortcode', function () {
return new ShortCode('{', '}', ['custom' => 'option']);
});
Log Decoded Output Debug placeholders by logging intermediate steps:
\Log::debug('Encoded:', [$encodedString]);
\Log::debug('Decoded:', [ShortCode::decode($encodedString, $data)]);
Test Edge Cases Test with:
{}).$data (throws UndefinedArrayKeyException).{user@domain.com}).Custom Decoders
Override the decode method to add logic (e.g., URL encoding):
ShortCode::extend(function ($string, $data) {
return str_replace(['{url}', '{base_url}'], [url('/'), url()->base()], $string);
});
Database Storage Store encoded strings in the DB and decode during retrieval:
// Migration
$table->text('encoded_template')->nullable();
// Usage
$decoded = ShortCode::decode($record->encoded_template, $context);
Blade Integration Create a Blade directive for seamless template rendering:
Blade::directive('shortcode', function ($expression) {
return "<?php echo \\Adrianbaez\\ShortCodeBundle\Facades\\ShortCode::decode($expression, []); ?>";
});
Usage:
@shortcode('Hello {name}!')
How can I help you explore Laravel packages today?