SnelleJelle
SnelleJelle

Reputation: 963

logging inside a class or entity

I'm trying to shift the error logging responsibility to my class/entity. Currently the only clean way to get an instance of the logger is from my controller, only to then pass it on to my entity.

Is there a clean way to get an instance of the logger inside my class or entity?

Same goes for the Entitymanager

edit: setter injection:

enter image description here

the error I'm getting is:

Fatal error: Call to a member function error() on null

because it's didn't call the setter

Upvotes: 0

Views: 1430

Answers (1)

Tobias Xy
Tobias Xy

Reputation: 2069

If you define your class as a service you must not call the constructor yourself. The service container will care about constructing the object.

Instead you have to get your logger like this (assuming you want to get it within a controller):

class MyController extends Controller {

    public function someAction() {
        // ...
        $test = $this->get('my_test');
        $test->doLog();
        // ...
    }
}

Also the correct service definition for you would be:

services:
    my_test:
        class: AppBundle\Entity\Test        
        calls:
             - [setLogger, ["@logger"]]

The arguments key is used to pass arguments to the constructor of the class. But you are using setter injection, so the arguments key is wrong here.

Upvotes: 1

Related Questions