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

artplus_f/browscap-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Add the package via Composer:

    composer require fontai/browscap-bundle
    

    Register the bundle in config/bundles.php (if not auto-discovered):

    return [
        // ...
        Fontai\BrowscapBundle\FontaiBrowscapBundle::class => ['all' => true],
    ];
    
  2. Publish Configuration Publish the default config (if needed):

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

    This creates config/browscap.php. Key settings include:

    • browscap_path: Path to your Browscap file (e.g., vendor/crossjoin/browscap/browscap.ini).
    • cache_enabled: Enable caching for performance (default: true).
    • cache_ttl: Cache TTL in seconds (default: 86400 for 24h).
  3. First Use Case: Detect Browser Capabilities Inject the Browscap service into a controller or service:

    use Fontai\BrowscapBundle\Service\Browscap;
    
    class UserAgentController extends Controller
    {
        public function __construct(private Browscap $browscap) {}
    
        public function showCapabilities(Request $request)
        {
            $userAgent = $request->userAgent();
            $browser   = $this->browscap->getBrowser($userAgent);
    
            return response()->json($browser->toArray());
        }
    }
    
    • Key Methods:
      • getBrowser(string $userAgent): Returns a Browser object with parsed capabilities.
      • isMobile(string $userAgent): Quick check for mobile devices.
      • isBot(string $userAgent): Detects bots/spiders.

Implementation Patterns

1. User-Agent Parsing Workflows

  • Dynamic Feature Detection Use the parsed data to conditionally load assets or apply CSS/JS:

    if ($browser->isMobile()) {
        return view('mobile')->with('features', $browser->getFeatures());
    }
    
    • Common Features: isIE(), isChrome(), getMajorVersion(), supportsFlash().
  • Bot/Spider Handling Block or redirect bots early in middleware:

    public function handle(Request $request, Closure $next)
    {
        if ($this->browscap->isBot($request->userAgent())) {
            abort(403, 'Bots not allowed.');
        }
        return $next($request);
    }
    

2. Integration with Laravel Services

  • Cache Integration Leverage Laravel’s cache for performance:

    $this->browscap->setCache(new RedisCache()); // Replace with your cache driver
    
    • Cache Key: Defaults to browscap_<md5(userAgent)>.
  • Event-Driven Logic Dispatch events when specific browsers are detected:

    if ($browser->isIE() && $browser->getMajorVersion() < 11) {
        event(new LegacyBrowserDetected($browser));
    }
    

3. Customizing Browscap Data

  • Extend the Browser Class Add custom methods to the Browser object (e.g., for analytics):

    // In a service provider
    $this->app->extend('browscap.browser', function ($browser, $app) {
        $browser->setCustomProperty('isEnterprise', $browser->isIE() && $browser->getCompanyName() === 'Microsoft');
        return $browser;
    });
    
  • Override Default Config Modify config/browscap.php to point to a custom Browscap file:

    'browscap_path' => storage_path('app/browscap.ini'),
    

Gotchas and Tips

Pitfalls

  1. Browscap File Updates

    • The crossjoin/browscap package requires manual updates to the Browscap file (e.g., via composer require crossjoin/browscap:dev-main).
    • Tip: Set up a cron job to update the file weekly:
      composer require crossjoin/browscap:dev-main --no-update && composer update crossjoin/browscap --with-all-dependencies
      
  2. Cache Invalidation

    • If you update the Browscap file, clear the cache:
      php artisan cache:clear
      
    • Tip: Use php artisan browscap:clear-cache if the bundle provides a command.
  3. User-Agent Spoofing

    • Malicious user agents may bypass detection. Validate against known patterns:
      if (strpos($userAgent, 'Mozilla/') === false) {
          // Likely spoofed or bot
      }
      

Debugging Tips

  • Log Parsed Data Dump the Browser object to debug:
    \Log::debug('Browser data:', $browser->toArray());
    
  • Check for Missing Features If getBrowser() returns null, verify:
    • The Browscap file exists at config('browscap.browscap_path').
    • The user agent string is valid (e.g., Mozilla/5.0 (Windows NT 10.0; ...)).

Extension Points

  1. Custom Browser Rules Extend the Browser class to add domain-specific logic:

    namespace App\Services;
    
    use Fontai\BrowscapBundle\Entity\Browser as BaseBrowser;
    
    class CustomBrowser extends BaseBrowser
    {
        public function isLegacy()
        {
            return $this->getMajorVersion() < 10 || $this->isIE();
        }
    }
    

    Bind it in a service provider:

    $this->app->bind('browscap.browser', function ($app) {
        return new CustomBrowser($app['browscap.browser']->getData());
    });
    
  2. Database Storage Store parsed browser data in a database for analytics:

    $browserData = $browser->toArray();
    UserAgentLog::create([
        'user_agent' => $request->userAgent(),
        'browser'    => json_encode($browserData),
        'ip'         => $request->ip(),
    ]);
    
  3. Performance Optimization

    • Disable caching for development:
      'cache_enabled' => env('APP_ENV') !== 'local',
      
    • Use a lighter Browscap file (e.g., browscap_lite.ini) if full features aren’t needed.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware