Installation
composer require digifa/mobile-detect-bundle
Ensure Digifa\MobileDetectBundle\MobileDetectBundle::class is registered in config/bundles.php.
Configuration Publish the default config:
php bin/console config:dump-reference DigifaMobileDetectBundle
Override in config/packages/digifa_mobile_detect.yaml:
digifa_mobile_detect:
redirect_mobile: true
mobile_url: '~mobile/'
tablet_url: '~tablet/'
desktop_url: '~desktop/'
First Use Case Check if the current request is mobile in a controller:
use Digifa\MobileDetectBundle\MobileDetect;
public function index(MobileDetect $detect)
{
if ($detect->isMobile()) {
return $this->redirectToRoute('mobile_home');
}
// Desktop logic
}
Automatic Redirects
Enable via redirect_mobile: true in config. The bundle hooks into Symfony’s event system (kernel.request) to redirect before rendering templates.
Conditional Rendering
Use the MobileDetect service in Twig:
{% if app.service('digifa_mobile_detect').isMobile() %}
{# Mobile-specific content #}
{% endif %}
Custom Detection Logic Extend the default detection by overriding the service:
# config/services.yaml
services:
Digifa\MobileDetectBundle\MobileDetect:
arguments:
$userAgent: '%kernel.user_agent%'
$mobileRegex: '~your_custom_regex~'
Route-Based Mobile Views Use route parameters or annotations to serve mobile/tablet-specific routes:
#[Route('/product/{id}', name: 'product_desktop')]
public function productDesktop(Product $product) { ... }
#[Route('/mobile/product/{id}', name: 'product_mobile')]
public function productMobile(Product $product) { ... }
Redirect logic in a base controller:
public function __construct(private MobileDetect $detect) {}
public function preflight(Request $request)
{
if ($this->detect->isMobile() && $request->getPathInfo() !== '/mobile/') {
return $this->redirectToRoute('product_mobile', ['id' => $request->attributes->get('id')]);
}
}
A/B Testing or Feature Flags
Combine with Symfony’s Feature component to toggle mobile-specific features:
if ($detect->isMobile() && Feature::isEnabled('mobile_feature')) {
// Enable mobile-only feature
}
Caching Headers
# config/packages/framework.yaml
framework:
http_cache:
invalidation:
exclude_paths: ['^/mobile/', '^/tablet/']
User-Agent Spoofing
User-Agent strings, which can be spoofed. Validate with additional checks (e.g., screen width via JavaScript) if security is critical.Route Conflicts
/mobile/, /tablet/) or subdomains (m.yourdomain.com).Performance Overhead
$detect = app()->has('digifa_mobile_detect') ? app('digifa_mobile_detect') : null;
Log Detection Results Add a debug endpoint to inspect detection:
#[Route('/_debug/mobile-detect')]
public function debugMobileDetect(MobileDetect $detect): JsonResponse
{
return new JsonResponse([
'isMobile' => $detect->isMobile(),
'isTablet' => $detect->isTablet(),
'userAgent' => $detect->getUserAgent(),
]);
}
Override Detection Logic
For testing, mock the MobileDetect service:
// tests/ControllerTest.php
protected function getMobileDetectMock(bool $isMobile = true): MobileDetect
{
$mock = $this->createMock(MobileDetect::class);
$mock->method('isMobile')->willReturn($isMobile);
return $mock;
}
Custom Device Lists
Extend the bundle’s device database by overriding the MobileDetect service and injecting a custom Mobile_Detect_Lib instance:
// src/Service/CustomMobileDetect.php
use Mobile_Detect_Lib;
class CustomMobileDetect extends MobileDetect
{
public function __construct()
{
$detect = new Mobile_Detect_Lib();
$detect->setUserAgent($_SERVER['HTTP_USER_AGENT']);
$this->setDetect($detect);
// Add custom device patterns
$detect->setCustomPatterns(['custom_pattern' => '~custom_regex~']);
}
}
Event-Based Redirects
Listen to the mobile_detect.redirect event to customize redirects:
// src/EventListener/MobileRedirectListener.php
use Digifa\MobileDetectBundle\Event\RedirectEvent;
class MobileRedirectListener
{
public function onRedirect(RedirectEvent $event)
{
if ($event->isMobile() && $event->getRequest()->getPathInfo() === '/admin') {
$event->setRedirectUrl('/desktop/admin');
}
}
}
Register in services.yaml:
services:
App\EventListener\MobileRedirectListener:
tags:
- { name: 'kernel.event_listener', event: 'mobile_detect.redirect', method: 'onRedirect' }
Tablet-Specific Logic
Use isTablet() to target tablets explicitly:
if ($detect->isTablet()) {
$this->addFlash('tablet', 'Optimized for tablets!');
}
URL Formats
mobile_url and tablet_url support Symfony’s router placeholders (e.g., ~mobile/{path}). Ensure trailing slashes match your routing conventions.Case Sensitivity
mobile_regex are case-sensitive. Use (?i) for case-insensitive matching:
digifa_mobile_detect:
mobile_regex: '~(?i)mobile~'
Environment-Specific Rules Disable redirects in dev environments:
# config/packages/dev/digifa_mobile_detect.yaml
digifa_mobile_detect:
redirect_mobile: false
How can I help you explore Laravel packages today?