Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: ACMEMyBundleListenerController
    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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...