Blogger Information
Blog 61
fans 0
comment 0
visits 53935
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
依赖容器实现解耦
笑颜常开的博客
Original
940 people have browsed it

<?php
//容器:也叫服务容器
//1.创建容器:本质就是一个类与它的实现绑定到一个关联数组
//2.服务注册:初始化这个关联数组,将工具类绑定到容器中;
//3.容器依赖:也叫依赖容器,调用的时候直接传一个容器对象即可,不用一个一个传具体对象
class Db
{
   public function connect()
   {
       return '数据库连接成功<br>';
   }
}

class Validate
{
   public function check()
   {
       return '数据验证成功<br>';
   }
}

class View
{
   public function display()
   {
       return '用户登录成功';
   }
}


class Container
{
//    创建一个空数组来保存工具类以及实现方法
   public $instance = [];
//    protected $instance = [];

//    $instance['类名']='类的实例化过程';
//将需要实例化的类与它的实现方法进行绑定:将对象容器初始化
   public function bind($abstract, Closure $process)
   {
       $this->instance[$abstract] = $process;
//        $this->instance['db'] = function(){
//            return new Db();
//        }
   }

//    创建特定类的实例
   public function make($abstract, $params = [])
   {
      return call_user_func_array($this->instance[$abstract], []);
   }
}

//二、服务注册:其实就是调用容器的bind()将对象注册到容器中
$container = new Container();
//将Db类绑定到容器中
$container->bind('db', function () {
   return new Db();
});
//将Validate类绑定到容器中
$container->bind('validate', function () {
   return new Validate();
});
//将View类绑定到容器中
$container->bind('view', function () {
   return new View();
});
var_dump($container->instance);


//三、容器注入:容器依赖,以所有用到的对象,以容器的方式,注入到当前的工作类中
class User
{
   public function login(Container $container)
   {
//        $container->make('db')实例化Db类,创建db类,链式调用
       echo $container->make('db')->connect();
       echo $container->make('validate')->check();
       echo $container->make('view')->display();
   }
}
$user=new User();
echo '<h1>依赖容器实现解耦</h1>';
echo $user->login($container);

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post