user2564926
user2564926

Reputation: 55

Passing Interface In Constructor Symfony PHP

I'm new to interfaces, could someone please advise when an interface is autowired in a method, since the interface has no functionality, where does the functionality come from in the method $logger->info() ? thanks

use Psr\Log\LoggerInterface;

public function index(LoggerInterface $logger)
{
    $logger->info('I just got the logger');
    $logger->error('An error occurred');

    $logger->critical('I left the oven on!', [
        // include extra "context" info in your logs
        'cause' => 'in_hurry',
    ]);

    // ...
}

Upvotes: 0

Views: 665

Answers (1)

adria
adria

Reputation: 1

Interfaces cannot be instantiated and they have no implemented code, so when you autowire an interface in a method, such as LoggerInterface, you are not asking for an actual instance of the interface itself, you are asking for a class implementing the LoggerInterface.

In this case, AbstractLogger is the one implementing LoggerInterface. This AbstractLogger abstract class is using the LoggerTrait which is the one implementing the functionality of $logger->info().

You can check it more in detail here: PSR-3

In summary:

  1. Symfony sees that index method requires a LoggerInterface.
  2. The Dependency Injection container checks its configuration to find a class that implements LoggerInterface
  3. The Dependency Injection container automatically creates a instance of AbstractLogger so you can use $logger->info implementation in LoggerTrait

Upvotes: 0

Related Questions