0

As I've been reading through the documentation and examples, I've found that a LoggerInterface is passed through the constructor of a dependency, as seen here, and this allows dependencies to output to the console.

My questions are:

  1. If I have multiple classes do I keep passing along a LoggerInterface in the constructor or is there a better practice for this? Or should I not even be passing it to these classes?

  2. If I want to make a class work with out a LoggerInterface, would I always just check if $this->logger is null and then act accordingly?

For example,

class ObjectOne {
    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct (LoggerInterface $logger) {
        $this->logger = $logger;
    }
}

class ObjectTwo {
    /**
     * @var ObjectOne[]
     */
    private $items;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct (LoggerInterface $logger) {
        $this->logger = $logger;
    }

    public function addObject () {
        $this->items[] = new ObjectOne($this->logger);
    }
}

1 Answer 1

0

In this case, the use of the LoggerInterface is nothing more than a type-hint.

If you pass an instance of a class (or anything else) that doesn't implement this interface, e.g:

$objectOne = new ObjectOne('randomstring');

An error will be thrown saying that the first argument of ObjectOne must be an instance of LoggerInterface, string given.

You can perfectly remove this type-hint, but then your class can be instantiated with a first argument of any type.
So, removing this check can produce unexpected errors, for instance if the first argument is not an instance of a class that implements the LoggerInterface, and you try to call a method that is not implemented by the class that the argument is an instance of.

Also, an interface allows to force classes to implement the same methods of those implemented by the interface, it's a kind of contract between classes.
And so you can have several different classes that implement the same interface and so respect the type-hint of your class constructor's first argument.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.