4

I'am trying to get details of devices who access our application. I have integrated "MobileDetectBundle" bundle in php symfony 3.4 version and followed the steps provided in the documentation. But I am getting the following error at this line

$mobileDetector = $this->get('mobile_detect.mobile_detector');

Code Snippet :

$mobileDetector = $this->get('mobile_detect.mobile_detector');
$mobileDetector->isMobile();
$mobileDetector->isTablet();

Error :

"Call to a member function get() on null"

Please help me to solve this issue.

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
Kiran Kumar
  • 167
  • 1
  • 2
  • 13

1 Answers1

3

The problem is with $this which assumed to be an instance of your controller class, but is null which means you are calling that somewhere (maybe inside controller constructor) where there is no $this yet.

the solution indeed is Dependency Injection. you would better inject that service into your controller (which is defined as a service automatically through auto-wiring) and use it inside your controller:

class MyController
{
    // ...

    protected $mobileDetector;

    public function __construct(MobileDetector $mobileDetector)
    {
        $this->mobileDetector = $mobileDetector;
        $this->mobileDetector->isMobile();
        $this->mobileDetector->isTablet();
    }

    // ...
}
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100