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

Devicedetect Bundle Laravel Package

crossknowledge/devicedetect-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require crossknowledge/devicedetect-bundle
    
  2. Enable the Bundle in config/bundles.php:
    CrossKnowledge\DeviceDetectBundle\CrossKnowledgeDeviceDetectBundle::class => ['all' => true],
    
  3. Configure in config/packages/crossknowledge_device_detect.yaml:
    cross_knowledge_device_detect:
        user_agent: '%kernel.request%'
    
  4. First Use Case: Detect device type in a controller:
    use CrossKnowledge\DeviceDetectBundle\DeviceDetector;
    
    public function index(DeviceDetector $detector)
    {
        $device = $detector->detect();
        return new Response('Detected: ' . $device->getClient('type'));
    }
    

Key Classes to Explore

  • DeviceDetector: Main service for detection.
  • Device: Holds parsed device data (OS, browser, etc.).
  • ClientHint: For handling HTTP headers like Sec-CH-UA.

Implementation Patterns

Common Workflows

1. Request-Based Detection

Inject DeviceDetector into controllers/services to parse the current request’s User-Agent:

public function show(DeviceDetector $detector, Request $request)
{
    $device = $detector->detect($request->headers->get('User-Agent'));
    $isMobile = $device->getClient('type') === 'mobile';
}

2. Caching Results

Cache detection results to avoid reprocessing the same User-Agent:

$cacheKey = 'device_' . md5($userAgent);
$device = $cache->get($cacheKey) ?? $detector->detect($userAgent);
$cache->set($cacheKey, $device, 3600); // Cache for 1 hour

3. Conditional Logic

Use detected data to modify responses (e.g., redirect mobile users to a different URL):

if ($device->getClient('type') === 'mobile') {
    return redirect()->to('/mobile');
}

4. Client Hints (Modern Browsers)

Leverage Sec-CH-UA headers for more accurate detection:

$clientHints = $request->headers->get('Sec-CH-UA');
$device = $detector->detect($userAgent, $clientHints);

5. Event Listeners

Trigger actions based on device detection (e.g., logging or analytics):

// src/EventListener/DeviceListener.php
public function onKernelRequest(GetResponseEvent $event)
{
    $device = $detector->detect($event->getRequest());
    // Log or track device data
}

Register in services.yaml:

services:
    App\EventListener\DeviceListener:
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Integration Tips

Twig Integration

Pass the DeviceDetector to Twig templates:

# config/packages/twig.yaml
twig:
    globals:
        device_detector: '@cross_knowledge_device_detect.device_detector'

Use in templates:

{% if device_detector.detect(app.request).getClient('type') == 'mobile' %}
    <link rel="stylesheet" href="{{ asset('css/mobile.css') }}">
{% endif %}

API Responses

Include device data in API responses for analytics:

return $this->json([
    'data' => $data,
    'device' => [
        'type' => $device->getClient('type'),
        'os' => $device->getOs('name'),
        'browser' => $device->getClient('name'),
    ],
]);

Testing

Mock the DeviceDetector in tests:

$mockDetector = $this->createMock(DeviceDetector::class);
$mockDetector->method('detect')->willReturn($mockDevice);
$this->container->set(DeviceDetector::class, $mockDetector);

Gotchas and Tips

Pitfalls

1. Outdated Data

  • The package uses matomo/device-detector (last updated 2021), which may not include modern devices/browsers.
  • Workaround: Manually update the underlying DeviceDetector rules or fork the package.

2. Performance Overhead

  • Parsing User-Agent strings can be slow for high-traffic sites.
  • Solution: Cache results aggressively (e.g., Redis) or use a lighter-weight alternative like mobiledetectlib.

3. Client Hints Not Always Available

  • Sec-CH-UA headers are only supported in Chrome/Edge (since ~2021).
  • Tip: Fall back to User-Agent if Sec-CH-UA is missing.

4. Symfony 6+ Compatibility

  • The bundle was last updated for Symfony 5. Test thoroughly in Symfony 6+.
  • Fix: Extend the bundle or use a wrapper service to handle deprecations.

5. False Positives/Negatives

  • Some devices (e.g., tablets) may be misclassified.
  • Debugging: Use $device->getClient('user_agent') to inspect raw input.

Debugging Tips

Inspect Raw Data

Dump the full device object to debug:

$device = $detector->detect($request->headers->get('User-Agent'));
dump($device->getAll());

Output includes:

  • client: Browser/device info.
  • os: Operating system.
  • bot: Bot detection.

Update Rules Manually

If detection is inaccurate, update the rules in:

$detector->getParser()->setRules([/* custom rules */]);

(See matomo/device-detector for rule formats.)

Log User-Agents

Log problematic User-Agent strings for analysis:

if ($device->getClient('type') === 'unknown') {
    \Log::warning('Unknown device: ' . $userAgent);
}

Extension Points

Custom Device Types

Extend detection logic by subclassing DeviceDetector:

class CustomDeviceDetector extends DeviceDetector
{
    protected function getCustomRules()
    {
        return [
            'custom_device' => '/CustomDevice\/1\.0/',
        ];
    }
}

Register as a service:

services:
    App\Service\CustomDeviceDetector:
        decorates: 'cross_knowledge_device_detect.device_detector'
        arguments: ['@App\Service\CustomDeviceDetector.inner']

Add Metadata

Attach custom metadata to the Device object:

$device->setCustom('is_enterprise', true);

Override Detection Logic

Replace the default detector entirely:

services:
    cross_knowledge_device_detect.device_detector:
        class: App\Service\MyCustomDetector
        arguments: ['@service_container']

Configuration Quirks

User-Agent Source

By default, the bundle uses Symfony’s RequestStack. To use a custom source:

cross_knowledge_device_detect:
    user_agent: 'app.request_stack' # Default
    # OR
    user_agent: '@custom.request_provider'

Disable Parsing

Skip parsing entirely (e.g., for performance):

cross_knowledge_device_detect:
    enabled: false

Then manually instantiate DeviceDetector without auto-configuration.

Language Support

The underlying matomo/device-detector supports multiple languages. Configure in PHP:

$detector->getParser()->setLanguage('en'); // Default
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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