Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Call to a member function get() on a non-object'?

Tags:

php

symfony

Using symfony2. I have a listener class that is attempting to call a method from a different class (a controller) like so:

        $authenticate = new AuthenticationController();
        $authenticate->isTokenValid($token);

And the controller isTokenValid method:

public function isTokenValid($token) {

    $conn = $this->get('database_connection');

Is throwing the error

Fatal error: Call to a member function get() on a non-object in /home/content/24/9254124/html/newsite/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php on line 246

If i load the controller method the proper way (using routing in the url) it works fine.

like image 587
Jonah Katz Avatar asked Oct 15 '12 22:10

Jonah Katz


1 Answers

Symfony2 uses Dependency Injection pattern, you have to inject container that holds all services (like database connection):

$authenticate = new AuthenticationController();
$authenticate->setContainer($this->container);
$authenticate->isTokenValid($token);

Of course I assume here that your listener class is ContainerAware

[+] To make your listener ContainerAware, pass @service_container to it (example form services.yml)

my.listener:
    class: ACME\MyBundle\ListenerController
    arguments: [ @service_container ]
    tags:
        - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
    kernel.event_listener:
        event: kernel.controller

and then in constructor of you listener class:

public function __construct($container = null){
    $this->container = $container;
}
like image 110
dev-null-dweller Avatar answered Sep 30 '22 02:09

dev-null-dweller