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

Browscap Bundle Laravel Package

browscap/browscap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require browscap/browscap-bundle
    

    Add the bundle to config/bundles.php (Laravel 5.4+) or AppKernel.php (older versions):

    Browscap\BrowscapBundle\BrowscapBundle::class,
    
  2. Configuration: Publish the default config (if needed):

    php artisan vendor:publish --tag=browscap-config
    

    Update config/browscap.php with your preferred remote_ini_url or local path to the Browscap INI file.

  3. First Use Case: Inject the Browscap\BrowscapBundle\Service\BrowscapService into a controller or service:

    use Browscap\BrowscapBundle\Service\BrowscapService;
    
    public function __construct(BrowscapService $browscap)
    {
        $this->browscap = $browscap;
    }
    
    public function detect(Request $request)
    {
        $userAgent = $request->header('User-Agent');
        $browser = $this->browscap->getBrowser($userAgent);
        return response()->json($browser);
    }
    

Implementation Patterns

Common Workflows

  1. User-Agent Parsing: Use the service to parse user-agent strings in middleware, controllers, or services:

    $browser = $this->browscap->getBrowser($userAgent);
    $isMobile = $browser->isMobileDevice;
    $browserName = $browser->browser;
    
  2. Middleware for Browser Detection: Create middleware to attach browser data to the request:

    namespace App\Http\Middleware;
    
    use Closure;
    use Browscap\BrowscapBundle\Service\BrowscapService;
    
    class DetectBrowser
    {
        protected $browscap;
    
        public function __construct(BrowscapService $browscap)
        {
            $this->browscap = $browscap;
        }
    
        public function handle($request, Closure $next)
        {
            $userAgent = $request->header('User-Agent');
            $request->browser = $this->browscap->getBrowser($userAgent);
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\DetectBrowser::class,
    ];
    
  3. Conditional Logic: Use browser data to customize responses or enforce policies:

    if ($request->browser->isMobileDevice) {
        return redirect()->route('mobile.home');
    }
    
  4. Caching: Cache the parsed browser data to avoid repeated parsing (e.g., using Laravel's cache):

    $cacheKey = 'browser_' . md5($userAgent);
    $browser = cache()->remember($cacheKey, now()->addHours(1), function () use ($userAgent) {
        return $this->browscap->getBrowser($userAgent);
    });
    

Integration Tips

  • Symfony Integration: If using Symfony components, leverage the Browscap\BrowscapBundle\DependencyInjection\BrowscapExtension for configuration.
  • API Responses: Serialize browser data for API responses:
    return response()->json([
        'browser' => [
            'name' => $browser->browser,
            'version' => $browser->version,
            'platform' => $browser->platform,
        ],
    ]);
    
  • Local Development: For local testing, use a local Browscap INI file (download from Browscap) and point remote_ini_url to it:
    browscap:
        remote_ini_url: /path/to/local/browscap.ini
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package: The package is archived and lacks active maintenance. Consider alternatives like mobile-detect or ua-parser if long-term support is critical.

  2. Remote INI Dependency: The default configuration relies on a remote INI file (stream.php?BrowsCapINI). This introduces:

    • Latency on first request.
    • Potential downtime if the remote server is unavailable.
    • Solution: Use a local INI file and update it periodically via a cron job or script.
  3. Outdated Data: The Browscap database may not include the latest browsers/versions. Update the INI file regularly:

    # Example script to fetch and update local INI
    curl -o public/browscap.ini http://tempdownloads.browserscap.com/stream.php?BrowsCapINI
    
  4. Memory Usage: Parsing large INI files can consume significant memory. Monitor usage in high-traffic applications.

  5. Case Sensitivity: User-agent strings are case-insensitive, but the INI file may have quirks. Normalize inputs if issues arise:

    $userAgent = strtolower($request->header('User-Agent'));
    

Debugging

  • Verify INI File: Check if the INI file is being loaded correctly by inspecting the Browscap\BrowscapBundle\Service\BrowscapService logs or adding debug output:

    $browser = $this->browscap->getBrowser($userAgent);
    if (!$browser) {
        \Log::error('Browscap: No match for UA', ['ua' => $userAgent]);
    }
    
  • Test with Known UAs: Use known user-agent strings to verify functionality:

    $userAgents = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1',
    ];
    foreach ($userAgents as $ua) {
        $browser = $this->browscap->getBrowser($ua);
        dd($browser);
    }
    

Extension Points

  1. Custom INI Paths: Override the INI path in config:

    browscap:
        remote_ini_url: null
        ini_path: /custom/path/to/browscap.ini
    
  2. Extend Browser Data: Add custom properties to the browser object by extending the service or using a decorator pattern:

    class CustomBrowscapService extends BrowscapService
    {
        public function getBrowser($userAgent)
        {
            $browser = parent::getBrowser($userAgent);
            if ($browser) {
                $browser->isSupported = $this->isBrowserSupported($browser);
            }
            return $browser;
        }
    
        protected function isBrowserSupported($browser)
        {
            // Custom logic
            return $browser->majorver >= 90;
        }
    }
    

    Bind the custom service in config/services.php:

    'browscap' => App\Services\CustomBrowscapService::class,
    
  3. Event Listeners: Dispatch events when browser data is parsed (requires custom event system or middleware):

    // Example pseudo-code
    event(new BrowserDetected($browser, $userAgent));
    

Configuration Quirks

  • Caching: The bundle does not include built-in caching. Implement caching at the application level (e.g., Laravel's cache) for performance.
  • Environment-Specific Configs: Use Laravel's environment-based configs to switch between local/remote INI files:
    browscap:
        remote_ini_url: <%= env('BROWSCAP_REMOTE_INI', 'http://tempdownloads.browserscap.com/stream.php?BrowsCapINI') %>
        ini_path: <%= env('BROWSCAP_LOCAL_INI', null) %>
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
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