Installation:
composer require backend2-plus/is-mobile-bundle
No additional configuration is required for basic usage.
First Use Case:
Inject the IsMobile service into a controller or command to check if the current request originates from a mobile device:
use IsMobile\IsMobileBundle\IsMobile;
public function index(IsMobile $isMobile): Response
{
$isMobileDevice = $isMobile->isMobile();
// Use $isMobileDevice (bool) in your logic
}
Twig Integration (Optional):
Add to config/packages/twig.yaml:
globals:
isMobileHelper: '@IsMobile\IsMobileBundle\IsMobile'
Then use in templates:
{% if isMobileHelper.IsMobile() %}
<div>Mobile-specific content</div>
{% endif %}
Request-Based Logic: Use in controllers/middleware to serve mobile-specific responses:
public function show(IsMobile $isMobile): Response
{
return $isMobile->isMobile()
? $this->renderMobileView()
: $this->renderDesktopView();
}
Middleware for Routing: Create a middleware to redirect or modify behavior:
public function handle(Request $request, Closure $next, IsMobile $isMobile): Response
{
if ($isMobile->isMobile()) {
$request->attributes->set('mobile', true);
}
return $next($request);
}
Static Method Usage (v1.0.8+): Access via static calls where dependency injection isn’t available:
$isMobile = IsMobile::isMobile($request);
Twig Globals for Templates: Dynamically adjust UI based on device:
{% if isMobileHelper.IsMobile() %}
{{ include('mobile_nav.html.twig') }}
{% else %}
{{ include('desktop_nav.html.twig') }}
{% endif %}
IsMobile service in PHPUnit:
$this->mock(IsMobile::class)
->shouldReceive('isMobile')
->andReturn(true);
User-Agent Spoofing:
User-Agent strings, which can be spoofed. Validate results in critical paths (e.g., financial transactions).Tablet Detection:
$isTablet = IsMobile::isTablet($request);
Caching Headers:
isMobile() unless explicitly needed.Static Method Limitation:
IsMobile::isMobile($request)) bypass Symfony’s DI container. Prefer dependency injection for testability.$userAgent = $request->headers->get('User-Agent');
$this->logger->debug('User-Agent:', ['agent' => $userAgent]);
Custom Detection Logic:
Extend the service by overriding the isMobile() method:
class CustomIsMobile extends IsMobile
{
public function isMobile(): bool
{
return parent::isMobile() || $this->isCustomDevice();
}
}
Register the custom service in services.yaml:
IsMobile\IsMobileBundle\IsMobile: '@app.custom_is_mobile'
Add Device-Specific Methods: Extend the bundle to include tablet/laptop detection:
public function isTablet(): bool { /* ... */ }
public function isLaptop(): bool { /* ... */ }
Configuration: While the bundle has no public config options, you can bind custom logic via DI:
# config/services.yaml
IsMobile\IsMobileBundle\IsMobile:
arguments:
$customRules: !tagged 'mobile.detection.rule'
symfony/mobile-detector-bundle for broader device support if needed.isMobile() in loops or critical paths.isMobile() is true").How can I help you explore Laravel packages today?