PHP DI and casting interface

1.8k Views Asked by At

I do not understand, for example I'm using php-di container, I have ClassA and ClassB, both of them are implements Intreface1 And I'm creating objects of this two classes thru DI

Now when I'm injecting ClassA to the constructor I need inject exactly this class, which crate a dependency of this classA, not an Intreface1

Can I somehow say that this particular ClassA should implement intrefeca1 ? In docs of PHP-DI I found

  // mapping an interface to an implementation
    'LoggerInterface' => DI\create('MyLogger'),

But I do not understand how it works, LoggerIntreace it's just a string which maps this text to to the object

1

There are 1 best solutions below

0
On BEST ANSWER

You can inject "by interface"

example with monolog and php-di, you say :

use Monolog\Logger;

use Psr\Log\LoggerInterface;
...
  LoggerInterface::class => \DI\autowire(Logger::class)

and now in your constructor, you can inject

public function __construct(
        \Psr\Log\LoggerInterface $logger
    ) {

        $this->logger = $logger;
    }