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

Mobile Detect Bundle Laravel Package

david221189av/mobile-detect-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tattali/mobile-detect-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Tattali\MobileDetectBundle\TattaliMobileDetectBundle::class => ['all' => true],
    ];
    
  2. Configuration: Publish the default config:

    php bin/console tattali:mobile-detect:install
    

    Edit config/packages/tattali_mobile_detect.yaml to define:

    • Mobile/desktop routes (e.g., mobile_route: '/mobile', desktop_route: '/desktop').
    • Excluded routes (e.g., excluded_routes: ['/admin']).
    • Device detection thresholds (e.g., tablet_user_agent_patterns).
  3. First Use Case: Trigger detection in a controller:

    use Tattali\MobileDetectBundle\Service\MobileDetectService;
    
    class HomeController extends AbstractController
    {
        public function index(MobileDetectService $detectService)
        {
            if ($detectService->isMobile()) {
                return $this->redirectToRoute('mobile_home');
            }
            // Desktop logic...
        }
    }
    

Implementation Patterns

Core Workflows

  1. Route-Based Redirection: Use the MobileDetectService to redirect users automatically:

    # config/routes.yaml
    mobile_home:
        path: /mobile
        controller: App\Controller\MobileController::index
    
    // Controller
    public function index(MobileDetectService $detectService)
    {
        if ($detectService->isMobile()) {
            return $this->redirectToRoute('mobile_home');
        }
        return $this->render('desktop/home.html.twig');
    }
    
  2. Twig Integration: Pass the service to templates for conditional rendering:

    {% if mobileDetect.isMobile() %}
        {{ include('mobile/_header.html.twig') }}
    {% else %}
        {{ include('desktop/_header.html.twig') }}
    {% endif %}
    

    Register the service in Twig:

    # config/packages/twig.yaml
    twig:
        globals:
            mobileDetect: '@tattali_mobile_detect.mobile_detect'
    
  3. Dynamic Route Switching: Override routes in MobileDetectService for complex logic:

    $detectService->setMobileRoute('/custom-mobile-path');
    $detectService->setDesktopRoute('/custom-desktop-path');
    
  4. Event-Based Detection: Listen for mobile.detect events to customize behavior:

    // src/EventListener/MobileDetectListener.php
    class MobileDetectListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                MobileDetectEvents::DETECT => 'onMobileDetect',
            ];
        }
    
        public function onMobileDetect(MobileDetectEvent $event)
        {
            if ($event->isMobile() && $event->getUserAgent()->isTablet()) {
                $event->setMobileRoute('tablet_specific_route');
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. User-Agent Overrides:

    • Some devices (e.g., bots, custom clients) may spoof user agents. Validate with:
      if ($detectService->isMobile() && !$detectService->isBot()) {
          // Proceed with mobile logic
      }
      
  2. Caching Headers:

    • Mobile detection relies on User-Agent. Ensure caching headers (e.g., Cache-Control) don’t interfere:
      # config/packages/framework.yaml
      http_client:
          default_options:
              headers:
                  'Cache-Control': 'no-cache'
      
  3. Route Exclusions:

    • Misconfigured excluded_routes may break expected behavior. Test with:
      php bin/console debug:router | grep excluded
      
  4. Tablet Detection:

    • Default tablet patterns may misclassify devices. Extend via config:
      tattali_mobile_detect:
          tablet_user_agent_patterns:
              - 'iPad'
              - 'Android.*Tablet'
              - 'Kindle'
      

Debugging

  1. Log User Agents: Add a debug endpoint to inspect requests:

    // src/Controller/DebugController.php
    class DebugController extends AbstractController
    {
        public function userAgent(MobileDetectService $detectService)
        {
            return $this->json([
                'isMobile' => $detectService->isMobile(),
                'isTablet' => $detectService->isTablet(),
                'userAgent' => $detectService->getUserAgent()->getUserAgentString(),
            ]);
        }
    }
    
  2. Event Debugging: Dump MobileDetectEvent data in a subscriber:

    public function onMobileDetect(MobileDetectEvent $event)
    {
        file_put_contents(
            'debug/mobile_detect.log',
            print_r($event->toArray(), true)
        );
    }
    

Extension Points

  1. Custom Detection Logic: Extend the MobileDetectService:

    // src/Service/CustomMobileDetectService.php
    class CustomMobileDetectService extends MobileDetectService
    {
        public function isMobile()
        {
            if ($this->getUserAgent()->is('iPhone') && $this->isSmallScreen()) {
                return true;
            }
            return parent::isMobile();
        }
    
        private function isSmallScreen(): bool
        {
            // Custom logic (e.g., check for viewport width)
        }
    }
    

    Register as a service:

    services:
        tattali_mobile_detect.mobile_detect:
            class: App\Service\CustomMobileDetectService
            arguments: ['@request_stack']
    
  2. Database-Backed Device Rules: Store device patterns in a database and hydrate the service:

    // src/Service/DatabaseMobileDetectService.php
    class DatabaseMobileDetectService extends MobileDetectService
    {
        public function __construct(
            RequestStack $requestStack,
            EntityManagerInterface $em
        ) {
            $this->em = $em;
            parent::__construct($requestStack);
        }
    
        public function isMobile(): bool
        {
            $patterns = $this->em->getRepository(DevicePattern::class)
                ->findBy(['type' => 'mobile']);
            $this->setUserAgentPatterns($patterns);
            return parent::isMobile();
        }
    }
    
  3. Geolocation Hybrid Detection: Combine with geolocation services (e.g., geoip2/geoip2) for region-specific mobile handling:

    public function isMobile(): bool
    {
        $isMobile = parent::isMobile();
        $geo = $this->geoService->getLocation();
        if ($isMobile && $geo->getCountry()->getIsoCode() === 'US') {
            return $this->isUsMobileDevice();
        }
        return $isMobile;
    }
    
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