Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Short Code Bundle Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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"
    
  2. 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!"
    
  3. 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']
    );
    

Implementation Patterns

Common Workflows

  1. 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);
    
  2. API Response Wrapping Standardize API responses with consistent placeholders:

    $response = [
        'message' => ShortCode::decode('Data fetched for {user}', ['user' => $request->user()->name]),
        'data' => $data,
    ];
    
  3. Localization with Placeholders Combine with Laravel’s localization:

    $greeting = __('welcome.message', ['name' => ShortCode::decode('{user.name}', $user)]);
    

Integration Tips

  • 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('{{', '}}');
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • Last release in 2018; test thoroughly in your Laravel version (may require polyfills for newer PHP/Laravel).
    • Check for compatibility with your str_replace or template engine logic.
  2. No Built-in Security

    • Decoded strings may expose sensitive data if placeholders are user-controlled. Sanitize inputs:
      $safeData = array_map('htmlspecialchars', $userInput);
      ShortCode::decode($template, $safeData);
      
  3. 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.
    
  4. 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']);
    });
    

Debugging Tips

  • 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:

    • Empty placeholders ({}).
    • Missing keys in $data (throws UndefinedArrayKeyException).
    • Special characters in placeholders ({user@domain.com}).

Extension Points

  1. 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);
    });
    
  2. 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);
    
  3. 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}!')
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor