Mobile Detect

repository·4.x·Indexed 27 days ago

https://github.com/serbanghita/mobile-detect

A lightweight PHP library used to detect mobile devices and tablets by inspecting User-Agent strings and HTTP headers. It supports detection of specific platforms (iOS, Android), brands (Samsung), and browsers, and integrates with PSR-16 cache interfaces and Amazon CloudFront device detection headers.

Tokens
5.2K
Snippets
20
Records
35
Agent score
91%

What's inside mobile-detect

  1. Understand the role of Simple Cache PSR-16 interfaces

    4.x
    This repository contains the interfaces related to the PSR-16 (Simple Cache) standard. It is important to note that this package is not a cache implementation itself; it only defines the interfaces that a cache implementation must follow. To actually store data, you must use a package that implements this specification.
  2. Use Amazon CloudFront device detection headers

    4.x

    MobileDetect automatically recognizes and uses Amazon CloudFront headers if device detection is enabled on your distribution.

    use Detection\MobileDetect;
    
    // Automatically uses:
    // - HTTP_CLOUDFRONT_IS_MOBILE_VIEWER
    // - HTTP_CLOUDFRONT_IS_TABLET_VIEWER
    // - HTTP_CLOUDFRONT_IS_DESKTOP_VIEWER
    
    $detect = new MobileDetect();
    
    if ($detect->isMobile()) {
        // Mobile device detected via CloudFront
    }
  3. Run all pre-release validation checks via Docker Compose

    4.x

    To run the full suite of pre-release validation checks (including unit tests, performance benchmarks, linting, and static analysis) in a controlled PHP environment, use the runAll service. This acts as a pre-release gate.

    docker compose -p mobile-detect up --build runAll
  4. Integrate MobileDetect with Laravel or Symfony

    4.x

    MobileDetect can be easily integrated into modern frameworks via Middleware (Laravel) or Dependency Injection (Symfony).

    // Laravel Middleware Example
    namespace App\Http\Middleware;
    
    use Closure;
    use Detection\MobileDetect;
    use Illuminate\Http\Request;
    
    class DetectMobileDevice
    {
        public function handle(Request $request, Closure $next)
        {
            $detect = new MobileDetect();
            $request->attributes->set('is_mobile', $detect->isMobile());
            $request->attributes->set('is_tablet', $detect->isTablet());
            return $next($request);
        }
    }
    
    // Symfony Service Example (config/services.yaml)
    // services:
    //     Detection\MobileDetect:
    //         public: true
  5. Add new device models to Mobile-Detect

    4.x

    To add support for new tablet or phone models, follow this three-step methodology:

    1. Identify new models: Research vendor websites (e.g., Samsung's regional sites), use GSMArena to find specific SM-XXXX model variants, or check SamMobile. Cross-reference these with existing regex in src/MobileDetect.php and test fixtures in tests/providers/vendors/{Vendor}.php to avoid duplicates.
    2. Find User-Agent strings: Search UA databases (user-agents.net, whatismybrowser.com, etc.) or search for the specific model number + "user agent". If the device is too new, construct a UA string using the standard Chrome pattern with the device's Android version and a contemporary Chrome version.
    3. Add to codebase:
      • Update the appropriate regex array in src/MobileDetect.php (e.g., $tabletDevices['SamsungTablet']).
      • Add new test fixture entries in tests/providers/vendors/{Vendor}.php.
      • Verify the changes by running the test suite.
    vendor/bin/phpunit -v -c tests/phpunit.xml
  6. Handle long-running processes and batch processing

    4.x

    When using MobileDetect in workers, daemons (RoadRunner, Swoole, etc.), or batch processing scripts, ensure you manage the cache to prevent memory exhaustion. The bundled cache is bounded by default, but you can manually clear() it periodically.

    use Detection\MobileDetect;
    use Detection\Cache\Cache;
    
    $detect = new MobileDetect();
    $cache = $detect->getCache();
    
    $iterationCount = 0;
    
    while ($userAgent = getNextUserAgentFromQueue()) {
        $detect->setUserAgent($userAgent);
    
        $isMobile = $detect->isMobile();
        $isTablet = $detect->isTablet();
    
        processDevice($userAgent, $isMobile, $isTablet);
    
        $iterationCount++;
    
        // Periodically reset the cache to manage memory
        if ($iterationCount % 1000 === 0 && $cache instanceof Cache) {
            $cache->clear();
        }
    }
  7. Run individual validation services via Docker Compose

    4.x

    You can run specific validation tasks individually using Docker Compose. Each service uses a specific PHP image tailored to the task (e.g., Xdebug for coverage, Alpine for performance/linting).

    # Unit tests with coverage
    docker compose -p mobile-detect up --build runUnitTests
    
    # Performance benchmarks
    docker compose -p mobile-detect up --build runPerfTests
    
    # Code style linting
    docker compose -p mobile-detect up --build runLinting
    
    # Static analysis
    docker compose -p mobile-detect up --build runQualityCheck
    
    # Generate JSON model (runs after all checks pass)
    docker compose -p mobile-detect up --build generateJsonModel
  8. Clean up Docker Compose resources

    4.x

    To remove the containers, networks, and volumes created by the mobile-detect project and clean up orphaned containers, use the down command with the --volumes and --remove-orphans flags.

    docker compose -p mobile-detect down --volumes --remove-orphans