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

Barcode Bundle Laravel Package

bitgrave/barcode-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require bitgrave/barcode-bundle
    

    Add the bundle to config/bundles.php:

    Paterik\BGBarcodeBundle\PaterikBGBarcodeBundle::class => ['all' => true],
    
  2. Basic Usage Generate a barcode in a controller:

    use Paterik\BGBarcodeBundle\Service\BarcodeService;
    
    class BarcodeController extends AbstractController
    {
        public function generate(BarcodeService $barcodeService)
        {
            $barcode = $barcodeService->getBarcode('EAN13', '123456789012');
            return new Response($barcode->render());
        }
    }
    
  3. First Use Case Render a barcode as an image in a Symfony template:

    <img src="{{ path('barcode_generate', {'type': 'EAN13', 'data': '123456789012'}) }}" alt="Barcode">
    

    Define the route in config/routes.yaml:

    barcode_generate:
        path: /barcode/{type}/{data}
        controller: Paterik\BGBarcodeBundle\Controller\BarcodeController::generate
    

Implementation Patterns

Core Workflows

  1. Dynamic Barcode Generation Use the BarcodeService to generate barcodes dynamically based on user input:

    $barcode = $barcodeService->getBarcode($type, $data, [
        'width' => 300,
        'height' => 100,
        'format' => 'png', // or 'svg', 'html'
    ]);
    
  2. Batch Processing Generate multiple barcodes in a loop (e.g., for invoices or product labels):

    foreach ($products as $product) {
        $barcode = $barcodeService->getBarcode('EAN13', $product->getEan());
        $this->saveBarcodeImage($barcode->render(), $product->id);
    }
    
  3. QR Code with Custom Error Correction Leverage QR code levels (L, M, Q, H) for varying data capacity:

    $qrCode = $barcodeService->getBarcode('QRCODE,M', 'https://example.com');
    
  4. SVG for Scalability Use SVG format for resolution-independent barcodes (e.g., in PDFs or responsive designs):

    $svgBarcode = $barcodeService->getBarcode('EAN13', '123456789012', ['format' => 'svg']);
    

Integration Tips

  • Twig Integration Extend Twig with a custom filter for inline barcode generation:

    // src/Twig/AppExtension.php
    public function getFilters()
    {
        return [
            new \Twig\TwigFilter('barcode', [$this, 'generateBarcodeFilter']),
        ];
    }
    
    public function generateBarcodeFilter(BarcodeService $barcodeService, string $type, string $data, array $options = [])
    {
        return $barcodeService->getBarcode($type, $data, $options)->render();
    }
    

    Usage in Twig:

    <img src="data:image/png;base64,{{ barcode('EAN13', '123456789012')|base64_encode }}" alt="Barcode">
    
  • API Responses Return barcodes as binary responses in APIs:

    return new BinaryFileResponse(
        $barcodeService->getBarcode('EAN13', $request->get('data'))->render(),
        200,
        ['Content-Type' => 'image/png']
    );
    
  • Configuration Override default settings in config/packages/paterik_bg_barcode.yaml:

    paterik_bg_barcode:
        default_format: svg
        default_width: 400
        default_height: 150
        image_driver: gd # or 'imagick'
    

Gotchas and Tips

Pitfalls

  1. Image Driver Dependencies

    • GD vs. ImageMagick: Ensure the correct PHP extension is installed (php-gd or php-imagick).
      • Debug: php -m | grep -E 'gd|imagick' to check availability.
    • Fallback: The bundle defaults to GD if ImageMagick is unavailable. Configure explicitly:
      paterik_bg_barcode:
          image_driver: gd
      
  2. Memory Limits

    • Large 2D barcodes (e.g., PDF417 or DataMatrix with complex data) may exceed PHP’s memory_limit.
    • Fix: Increase memory_limit in php.ini or generate barcodes in chunks:
      ini_set('memory_limit', '256M');
      
  3. Character Encoding

    • Non-ASCII data (e.g., UTF-8) may corrupt certain barcode types (e.g., CODE39).
    • Fix: Encode data explicitly:
      $barcodeService->getBarcode('EAN13', mb_convert_encoding($ean, 'ASCII'));
      
  4. Caching Static Barcodes

    • Regenerating the same barcode (e.g., for a product SKU) wastes resources.
    • Fix: Cache rendered barcodes:
      $cacheKey = 'barcode_' . md5($type . $data);
      $barcode = $cache->get($cacheKey, function() use ($barcodeService, $type, $data) {
          return $barcodeService->getBarcode($type, $data);
      });
      
  5. HTML Table Format Quirks

    • The html format renders barcodes as tables, which may not scale well.
    • Fix: Use CSS to style or prefer SVG/PNG for production.

Debugging

  • Validate Barcode Data Use the validate() method to check if data is compatible with the barcode type:

    if (!$barcodeService->getBarcode('EAN13', 'invalid_data')->validate()) {
        throw new \InvalidArgumentException('Invalid EAN13 data');
    }
    
  • Log Errors Enable debug mode to catch barcode generation issues:

    # config/packages/dev/paterik_bg_barcode.yaml
    paterik_bg_barcode:
        debug: true
    
  • Check Supported Types Ensure the barcode type exists (e.g., QRCODE,H for high error correction):

    $supportedTypes = $barcodeService->getSupportedTypes(); // Array of valid types
    

Extension Points

  1. Custom Barcode Types Extend the bundle by adding new barcode types via a custom service:

    // src/Service/CustomBarcodeService.php
    class CustomBarcodeService extends AbstractBarcodeService
    {
        public function getBarcode(string $type, string $data, array $options = [])
        {
            if ($type === 'CUSTOM') {
                return $this->generateCustomBarcode($data, $options);
            }
            return parent::getBarcode($type, $data, $options);
        }
    }
    

    Override the bundle’s service in config/services.yaml:

    Paterik\BGBarcodeBundle\Service\BarcodeService: '@custom_barcode_service'
    
  2. Post-Processing Hook into the render() method to modify output (e.g., add a logo):

    $barcode->render(function ($image) {
        $logo = imagecreatefrompng('logo.png');
        imagecopy($image, $logo, 10, 10, 0, 0, imagesx($logo), imagesy($logo));
        return $image;
    });
    
  3. Event Listeners Trigger events before/after barcode generation (e.g., log generation):

    // src/EventListener/BarcodeListener.php
    class BarcodeListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                Paterik\BGBarcodeBundle\Event\BarcodeEvents::PRE_RENDER => 'onPreRender',
            ];
        }
    
        public function onPreRender(BarcodeEvent $event)
        {
            $this->logger->info('Generating barcode', [
                'type' => $event->getType(),
                'data' => $event->getData(),
            ]);
        }
    }
    

Performance Tips

  • Reuse Instances Inject BarcodeService as a singleton to avoid recreating the service:

    // src/Controller/BarcodeController.php
    public function __construct(private BarcodeService $barcodeService) {}
    
  • Lazy Loading Defer barcode generation until the response phase (e

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