php简单介绍DI注入方法

2024年07月06日 建站教程

今天web建站小编给大家介绍一下关于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();
};
?>

本文链接:http://so.lmcjl.com/news/7951/

展开阅读全文
相关内容