php简单介绍DI注入方法

今天编程教程网小编给大家介绍一下关于php简单的DI注入方法,下面给大家看一下简单的依赖注入代码和高阶的依赖注入代码?

简单的依赖注入代码


<?php
class container
{
  private $adapter;
  
  public function __construct(adapter $adapter)
  {
    $this->adapter = $adapter;
  }
}
?>

高阶的依赖注入代码


<?php
class container
{
  public $instance = [];
  
  public function __set($name, $value)
  {
    $this->instance[$name] = $value;
  }
}

$container = new container();

$container->adapter = new adapter();
$container->autofelix = new autofelix();
?>

依赖注入的应用


<?php
class container
{
  public $instance = [];
  
  public function __set($name, $value)
  {
    $this->instance[$name] = $value;
  }
}
 
class adapter
{
  public $name = '我是调度器';
}
 
$container = new container();
$container->adapter = new adapter();

class autofelix
{
  private $container;
  
  public function __construct(container $container)
  {
    $this->container = $container;
  }
  
  public function who($class)
  {
    return $this->container->instance[$class]->name;
  }
}
 
$autofelix = new autofelix($container);
 
$who = $autofelix->who('adapter');

var_dump($who); //我是调度器
?>

依赖注入高阶优化


<?php
$container = new container();
$container->adapter = new adapter();

//高阶优化
$container = new container();
$container->adapter = function () {
  return new adapter();
};
?>
以上是编程学习网小编为您介绍的“php简单介绍DI注入方法”的全面内容,想了解更多关于 php入门 内容,请继续关注编程基础学习网。

本文标题为:php简单介绍DI注入方法

基础教程推荐