duanaoyuan7202
2018-08-12 14:03 阅读 44
已采纳

PHP DI和铸造界面

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条回答 默认 最新

  • 已采纳
    douxi1738 douxi1738 2018-08-12 14:20

    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;
        }
    
    点赞 评论 复制链接分享

相关推荐