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

Device Detector Laravel Package

matomo/device-detector

Parses User-Agent strings and browser Client Hints to identify device type (desktop/tablet/mobile/TV/console), client apps (browsers, media players, feed readers), operating systems, and device brand/model. Composer-ready PHP library.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Compatibility: The package is designed to integrate seamlessly with Laravel via built-in cache bridges (LaravelCache) and PSR-6/PSR-16 support. The Laravel-specific Cache\LaravelCache adapter ensures minimal friction in adoption.
  • Modularity: The library’s architecture allows for granular usage—from full device detection to lightweight bot checks—making it adaptable to microservices or monolithic Laravel apps.
  • Extensibility: Supports custom YAML parsers, cache backends, and parser overrides, enabling tailored behavior for niche use cases (e.g., legacy UAs or custom device rules).

Integration Feasibility

  • Low-Coupling Design: The package operates independently of Laravel’s core, requiring only the HTTP_USER_AGENT and optional Accept-CH headers. No database migrations or schema changes are needed.
  • Middleware Integration: Can be wrapped in Laravel middleware (e.g., DeviceDetectorMiddleware) to parse UAs globally, reducing boilerplate in controllers.
  • Service Container: Easily registerable as a Laravel service provider with dependency injection for reusable detection logic.

Technical Risk

  • Performance Overhead:
    • Default array caching is process-local; production deployments should use PSR6Bridge (e.g., Redis) to avoid redundant parsing.
    • Client Hints (Accept-CH) add ~50–100ms latency on first request but improve accuracy. Requires server configuration (e.g., Nginx Accept-CH: Sec-CH-UA).
  • False Positives/Negatives:
    • Accuracy depends on regex patterns in YAML files (updated via Matomo’s ecosystem). Custom devices may require manual rule additions.
    • Bot detection relies on a predefined list; emerging bots may slip through.
  • Dependency Bloat:
    • Core package is lightweight (~5MB), but YAML parsers (e.g., spyc) or cache adapters (e.g., symfony/cache) may add dependencies.

Key Questions

  1. Use Case Priority:
    • Is granular device detection (e.g., model/brand) needed, or are high-level checks (e.g., isMobile()) sufficient?
    • Will Client Hints be leveraged, or is HTTP_USER_AGENT alone adequate?
  2. Scaling Needs:
    • What’s the expected QPS? For high traffic, PSR-6 caching (Redis/Memcached) is critical.
  3. Maintenance:
    • Who will update device/bot rules if the library’s upstream patterns lag?
  4. Legacy Support:
    • Are there edge cases (e.g., custom UAs, internal tools) requiring custom parsers?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Cache: Prefer PSR6Bridge with Laravel’s cache driver (e.g., Redis) for distributed caching.
    • Middleware: Ideal for global UA parsing (e.g., app/Http/Middleware/DeviceDetector.php).
    • Service Provider: Register as a singleton for dependency injection:
      $this->app->singleton(DeviceDetector::class, function ($app) {
          $dd = new DeviceDetector($_SERVER['HTTP_USER_AGENT'], ClientHints::factory($_SERVER));
          $dd->setCache(new Cache\LaravelCache());
          return $dd;
      });
      
  • Testing:
    • Use Laravel’s Http tests to mock $_SERVER['HTTP_USER_AGENT'] and verify detection logic.
    • Test edge cases (e.g., malformed UAs, empty strings).

Migration Path

  1. Pilot Phase:
    • Integrate in a non-critical module (e.g., analytics dashboard) to validate accuracy and performance.
    • Compare detection results against a known dataset (e.g., UAParser).
  2. Full Rollout:
    • Replace ad-hoc UA parsing (e.g., strpos() hacks) with the library’s methods.
    • Deprecate legacy detection logic via Laravel’s deprecated() helper.
  3. Optimization:
    • Enable Client Hints if server supports it (Nginx/Apache config).
    • Profile parsing time with Laravel Debugbar to identify bottlenecks.

Compatibility

  • PHP Version: Requires PHP 7.4+ (Laravel 8+). Test with PHP 8.2+ for performance gains (JIT optimizations).
  • Laravel Version: Compatible with Laravel 8+ (PSR-15 middleware). For Laravel 7, use the LaravelCache adapter manually.
  • Database: No schema changes, but cache backends (e.g., Redis) may require configuration.
  • Third-Party Tools:
    • Analytics: Integrate with Matomo/Piwik for unified device tracking.
    • A/B Testing: Use device data to segment experiments (e.g., isMobile() → mobile-optimized flows).

Sequencing

  1. Setup:
    • Install via Composer: composer require matomo/device-detector.
    • Configure caching (e.g., Redis) in config/cache.php.
  2. Development:
    • Create a DeviceDetectorService facade for clean syntax:
      use DeviceDetector\DeviceDetector;
      facade(DeviceDetectorService::class, DeviceDetector::class);
      
    • Add middleware to parse UAs on every request.
  3. Testing:
    • Validate detection accuracy with real-world UAs (e.g., from access.log).
    • Load-test with 10K RPS to measure parsing latency.
  4. Deployment:
    • Roll out in stages (e.g., 10% traffic → full).
    • Monitor error logs for malformed UA strings.

Operational Impact

Maintenance

  • Updates:
    • Library updates are infrequent (quarterly). Monitor Matomo’s changelog for regex pattern changes.
    • Custom rules (e.g., for internal devices) must be manually maintained.
  • Dependencies:
    • Core package has no external dependencies. Cache/YAML parsers may require updates (e.g., spycsymfony/yaml).
  • Logging:
    • Log undetected UAs to a device_detection_unknown table for analysis:
      if (!$dd->isBot() && empty($dd->getDeviceName())) {
          \Log::warning("Unknown device UA: {$_SERVER['HTTP_USER_AGENT']}");
      }
      

Support

  • Troubleshooting:
    • Common issues:
      • False Negatives: Update YAML rules or add custom patterns.
      • Performance: Enable caching or upgrade PHP (8.2+).
      • Client Hints: Verify server headers (curl -I https://your-site.com).
    • Debug with:
      $dd->parse();
      \Log::debug($dd->getAll());
      
  • Community:
    • Matomo’s GitHub issues are responsive (~3-day resolution). For urgent fixes, fork and patch locally.

Scaling

  • Horizontal Scaling:
    • Distributed caching (Redis) is required for multi-server setups.
    • Avoid per-request parsing overhead by caching results in a CDN (e.g., Varnish).
  • Cold Starts:
    • First request in a PHP process may be slower due to YAML parsing. Use OpCache to mitigate.
  • Edge Cases:
    • High Traffic: Offload parsing to a queue (e.g., Laravel Queues) for non-critical paths.
    • Legacy Systems: For PHP <7.4, use the standalone autoload.php with spyc.

Failure Modes

Failure Scenario Impact Mitigation
Cache backend failure (Redis down) Increased parsing latency Fallback to array cache (degraded mode).
Malformed UA string Parsing errors Sanitize input or wrap in try-catch.
Outdated YAML rules False positives/negatives Set up a cron job to auto-update rules.
Client Hints unsupported Reduced accuracy Fall back to HTTP_USER_AGENT only.
PHP process crashes Lost in-memory cache Use Redis for persistence.

Ramp-Up

  • Onboarding:
    • Developers: 2-hour workshop to cover:
      • Basic usage (isMobile(), getClient()).
      • Middleware integration.
      • Custom rule creation.
    • QA: Test with 50+ UAs from UserAgentString.com.
  • Documentation:
    • Add a DEVICE_DETECTION.md to the project with:
      • Example middleware.
      • Common use cases (e.g., "Show mobile-friendly UI").
      • Troubleshooting checklist.
  • Training:
    • Record a Loom video demonstrating:
      • Installation.
      • Debugging a misclassified UA.
      • Updating custom rules.
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi