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

Dhl Bundle Laravel Package

dreipunktnull/dhl-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your Symfony project via Composer:

    composer require dreipunktnull/dhl-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Dreipunktnull\DHLBundle\DreipunktnullDHLBundle::class => ['all' => true],
    ];
    
  2. Configuration Configure the bundle in config/packages/dreipunktnull_dhl.yaml:

    dreipunktnull_dhl:
        api_key: '%env(DHL_API_KEY)%'
        sandbox: true # Use sandbox for testing
        timeout: 30
    
  3. First Use Case: Track a Shipment Use the DHLClient service to fetch shipment data:

    use Dreipunktnull\DHLBundle\Client\DHLClient;
    
    class ShipmentTracker
    {
        public function __construct(private DHLClient $dhlClient) {}
    
        public function trackShipment(string $trackingNumber): array
        {
            return $this->dhlClient->trackAndTrace($trackingNumber);
        }
    }
    

    Call it in a controller:

    $tracker = $this->container->get(ShipmentTracker::class);
    $result = $tracker->trackShipment('00340434161094042557'); // Sandbox test number
    

Implementation Patterns

Common Workflows

  1. Tracking Shipments Use the trackAndTrace method for real-time tracking:

    $shipment = $dhlClient->trackAndTrace('DHL123456789');
    // Returns array with status, location, etc.
    
  2. Batch Processing For multiple shipments, loop through tracking numbers:

    $trackingNumbers = ['DHL123', 'DHL456', 'DHL789'];
    foreach ($trackingNumbers as $number) {
        $status = $dhlClient->trackAndTrace($number);
        // Log or store results
    }
    
  3. Error Handling Wrap API calls in try-catch blocks:

    try {
        $result = $dhlClient->trackAndTrace($trackingNumber);
    } catch (\Dreipunktnull\DHLBundle\Exception\DHLException $e) {
        // Log error (e.g., invalid tracking number, API timeout)
        $this->logger->error('DHL API Error: ' . $e->getMessage());
    }
    
  4. Integration with Symfony Forms Add tracking number fields to forms and validate them:

    // In a form type
    $builder->add('trackingNumber', TextType::class, [
        'constraints' => [
            new Callback([$this, 'validateTrackingNumber']),
        ],
    ]);
    
  5. Caching Responses Cache frequent queries (e.g., for high-traffic pages):

    $cacheKey = 'dhl_tracking_' . $trackingNumber;
    $result = $this->cache->get($cacheKey);
    if (!$result) {
        $result = $dhlClient->trackAndTrace($trackingNumber);
        $this->cache->set($cacheKey, $result, 3600); // Cache for 1 hour
    }
    

Integration Tips

  • Environment Variables Store DHL_API_KEY in .env and use %env(DHL_API_KEY)% in config.
  • Dependency Injection Inject DHLClient into services/controllers for reusability.
  • Logging Log API responses for debugging:
    # config/services.yaml
    Dreipunktnull\DHLBundle\Client\DHLClient:
        arguments:
            $logger: '@logger'
    
  • Testing Use sandbox mode (sandbox: true) and test numbers from the README during development.

Gotchas and Tips

Pitfalls

  1. Sandbox vs. Production

    • Forgetting to disable sandbox: true in production can lead to failed requests.
    • Test numbers only work in sandbox mode.
  2. Rate Limiting DHL APIs may throttle requests. Implement retries with exponential backoff:

    use Symfony\Component\Stopwatch\Stopwatch;
    
    $stopwatch = new Stopwatch();
    $event = $stopwatch->start('dhl_retry');
    $attempts = 0;
    $maxAttempts = 3;
    
    while ($attempts < $maxAttempts) {
        try {
            return $dhlClient->trackAndTrace($trackingNumber);
        } catch (DHLException $e) {
            $attempts++;
            if ($attempts === $maxAttempts) throw $e;
            $event->lap();
            sleep($event->getDuration() * 2); // Exponential backoff
        }
    }
    
  3. Invalid Tracking Numbers Always validate tracking numbers before API calls (e.g., regex: ^\d{16,20}$ for DHL).

  4. Deprecated Methods The bundle is archived (no active maintenance). Avoid relying on undocumented features.

  5. Timeouts Default timeout (30s) may be insufficient for slow connections. Adjust in config:

    dreipunktnull_dhl:
        timeout: 60
    

Debugging

  • Enable Debug Mode Set debug: true in config to log raw API responses:

    dreipunktnull_dhl:
        debug: true
    

    Check logs in var/log/dev.log.

  • API Response Inspection Dump responses to identify issues:

    $result = $dhlClient->trackAndTrace($number);
    file_put_contents('debug_dhl.json', json_encode($result, JSON_PRETTY_PRINT));
    

Extension Points

  1. Custom Services Extend DHLClient to add domain-specific logic:

    class CustomDHLClient extends DHLClient
    {
        public function getDeliveryEstimate(string $trackingNumber): ?DateTime
        {
            $data = $this->trackAndTrace($trackingNumber);
            // Parse and return estimated delivery date
        }
    }
    
  2. Event Listeners Trigger events for tracking updates (e.g., notify users via email):

    // src/EventListener/DHLTrackingListener.php
    class DHLTrackingListener
    {
        public function onTrackingUpdate(TrackingEvent $event)
        {
            // Send email, update UI, etc.
        }
    }
    
  3. Override Templates Customize response handling by overriding bundle templates (if applicable).

Configuration Quirks

  • API Key Format Ensure the key is a string (no quotes in .env):
    DHL_API_KEY=your_api_key_here
    
  • SSL Verification Disable if using self-signed certificates (not recommended for production):
    dreipunktnull_dhl:
        verify_peer: false
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope