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

前端 未结 2 1027
独厮守ぢ
独厮守ぢ 2020-12-10 18:33

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

        $authenticate = new Authe         


        
相关标签:
2条回答
  • 2020-12-10 19:11

    I'm adding another answer because what @dev-null-dweller suggests is a bad practice: in almost every case you better to inject only the services you need — not the whole container:

    use Doctrine\DBAL\Connection;
    
    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }
    
    my_listener:
        arguments: [ @database_connection ]
    
    0 讨论(0)
  • 2020-12-10 19:29

    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;
    }
    
    0 讨论(0)
提交回复
热议问题