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],
];
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
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
Tracking Shipments
Use the trackAndTrace method for real-time tracking:
$shipment = $dhlClient->trackAndTrace('DHL123456789');
// Returns array with status, location, etc.
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
}
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());
}
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']),
],
]);
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
}
DHL_API_KEY in .env and use %env(DHL_API_KEY)% in config.DHLClient into services/controllers for reusability.# config/services.yaml
Dreipunktnull\DHLBundle\Client\DHLClient:
arguments:
$logger: '@logger'
sandbox: true) and test numbers from the README during development.Sandbox vs. Production
sandbox: true in production can lead to failed requests.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
}
}
Invalid Tracking Numbers
Always validate tracking numbers before API calls (e.g., regex: ^\d{16,20}$ for DHL).
Deprecated Methods The bundle is archived (no active maintenance). Avoid relying on undocumented features.
Timeouts Default timeout (30s) may be insufficient for slow connections. Adjust in config:
dreipunktnull_dhl:
timeout: 60
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));
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
}
}
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.
}
}
Override Templates Customize response handling by overriding bundle templates (if applicable).
.env):
DHL_API_KEY=your_api_key_here
dreipunktnull_dhl:
verify_peer: false
How can I help you explore Laravel packages today?