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

Shortcode Bundle Laravel Package

drinky78/shortcode-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the bundle via Composer:

    composer require drinky78/shortcode-bundle:dev-master
    

    Register the bundle in AppKernel.php:

    new MW\Bundle\ShortcodeBundle\MWShortcodeBundle(),
    
  2. First Use Case Create a simple shortcode handler:

    php app/console generate:bundle --namespace=MyProject/TestBundle --format=yml --dir=src
    

    Then create a shortcode class:

    // src/MyProject/TestBundle/Shortcode/DemoShortcode.php
    namespace MyProject\TestBundle\Shortcode;
    use MW\Bundle\ShortcodeBundle\Shortcode\BaseShortcode;
    
    class DemoShortcode extends BaseShortcode {
        public function parse($options) {
            return 'Hello, Shortcode!';
        }
    }
    
  3. Service Configuration Define the shortcode as a service in Resources/config/services.yml:

    services:
        myproject.shortcode.demo:
            class: MyProject\TestBundle\Shortcode\DemoShortcode
            tags:
                - { name: mw.shortcode, alias: demo }
    
  4. Usage in Twig Use the shortcode in your Twig templates:

    {{ shortcode('demo') }}
    

Implementation Patterns

Workflows

  1. Shortcode Registration

    • Service-Based Registration: Define shortcodes as services with the mw.shortcode tag.
    • Dynamic Registration: Register shortcodes programmatically in a bundle's Bootstrap class or event subscriber:
      $container->loadFromExtension('mw_shortcode', [
          'shortcodes' => [
              'demo' => 'myproject.shortcode.demo',
          ],
      ]);
      
  2. Handling Shortcode Options Parse and validate options in the parse() method:

    public function parse($options) {
        $name = $options['name'] ?? 'Guest';
        return "Hello, {$name}!";
    }
    

    Use in Twig:

    {{ shortcode('demo', { 'name': 'John' }) }}
    
  3. Integration with Content Management

    • Database Storage: Store shortcodes in a database table and fetch them dynamically:
      $shortcodes = $em->getRepository('MyProjectTestBundle:Shortcode')->findAll();
      foreach ($shortcodes as $shortcode) {
          $container->loadFromExtension('mw_shortcode', [
              'shortcodes' => [$shortcode->getAlias() => $shortcode->getServiceId()],
          ]);
      }
      
    • CMS Integration: Use with Symfony CMF or EasyAdmin to manage shortcodes via admin panels.
  4. Reusable Shortcode Components Extend BaseShortcode to create reusable components:

    class ButtonShortcode extends BaseShortcode {
        public function parse($options) {
            $url = $options['url'] ?? '#';
            $text = $options['text'] ?? 'Click Me';
            return "<a href=\"{$url}\">{$text}</a>";
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Early Prototype Limitations

    • No Quoted Attributes: Avoid using var="value" in shortcodes; only unquoted attributes are supported.
    • No Closing Tags: Shortcodes like [demo]...[/demo] are not supported; use only self-closing tags like [demo].
    • No Namespace Support: Shortcode aliases must be unique globally.
  2. Service Configuration Issues

    • Incorrect Tag Name: Ensure the service tag is exactly mw.shortcode (case-sensitive).
    • Circular Dependencies: Avoid circular dependencies when dynamically registering shortcodes.
  3. Debugging Tips

    • Check Registered Shortcodes: Use the mw_shortcode.list command to verify registered shortcodes:
      php app/console mw_shortcode:list
      
    • Log Shortcode Parsing: Add debug logs in the parse() method to trace execution:
      public function parse($options) {
          \Log::debug('Shortcode options:', $options);
          return 'Content';
      }
      
  4. Performance Considerations

    • Caching: Cache shortcode outputs if they are static or rarely changed:
      public function parse($options) {
          $cacheKey = md5(serialize($options));
          if ($cache = $this->get('cache')->get($cacheKey)) {
              return $cache;
          }
          $content = 'Dynamic content';
          $this->get('cache')->set($cacheKey, $content, 3600);
          return $content;
      }
      
  5. Extension Points

    • Custom Shortcode Parsers: Extend the bundle by creating a custom parser for advanced use cases (e.g., nested shortcodes).
    • Event Listeners: Use Symfony events to intercept shortcode parsing:
      $dispatcher->addListener('mw_shortcode.parse', function($event) {
          $event->setContent('Modified: ' . $event->getContent());
      });
      
  6. Testing

    • Unit Testing Shortcodes: Test shortcode handlers in isolation:
      public function testParseShortcode() {
          $shortcode = new DemoShortcode();
          $this->assertEquals('Hello, John!', $shortcode->parse(['name' => 'John']));
      }
      
    • Integration Testing: Test shortcode rendering in Twig templates using PHPUnit's TwigTestCase.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle