zoukankan      html  css  js  c++  java
  • 简单DI

    <?php
    class DI
    {
        private $container;
    
        public function set($key, $obj, ...$args)
        {
            $this->container[$key] = [
                'obj'    => $obj,
                'params' => $args
            ];
        }
    
    
        public function delete($key)
        {
            unset($this->container[$key]);
        }
    
        public function clear()
        {
            $this->container = [];
        }
    
    
        public function get($key)
        {
            if (isset($this->container[$key])) {
                $res = $this->container[$key];
                if (is_object($res['obj']) && !is_callable($res['obj'])) {
                    return $res['obj'];
                } elseif (is_callable($res['obj'])) {
                    $this->container[$key]['obj'] = call_user_func($res['obj']);
                    return $this->container[$key]['obj'];
                } elseif (is_string($res['obj']) && class_exists($res['obj'])) {
                    $reflection                   = new ReflectionClass ($res['obj']);
                    $ins                          = $reflection->newInstanceArgs($res['params']);
                    $this->container[$key]['obj'] = $ins;
                    return $this->container[$key]['obj'];
                } else {
                    return $res['obj'];
                }
            } else {
                return null;
            }
        }
    }
    
    class Test1
    {
        public function show()
        {
            echo "hello World 
    ";
        }
    }
    
    class Test2
    {
        public function __construct($name)
        {
            echo '我是参数' . $name . PHP_EOL;
        }
    
        function show()
        {
            echo "我是test2";
        }
    }
    
    class Test4
    {
        public function show()
        {
            echo "test4";
        }
    }
    
    $DI = new DI();
    
    $DI->set('name', 'zhangsan');
    
    echo "注入字符串" . $DI->get('name') . PHP_EOL;
    
    $test1 = new Test1();
    
    $DI->set('test1', $test1);
    
    echo "获取对象" . $DI->get('test1')->show() . PHP_EOL;
    
    
    $DI->set('test2', Test2::class, 'zhangsa');
    
    $DI->get('test2')->show();
    
    
    $DI->set('test3', function () {
        return new Test4();
    });
    
    $DI->get('test3')->show();
  • 相关阅读:
    png格式的img元素直接设置背景色、border-radius等属性,不需再包裹div造成冗余
    :before伪元素的灵活用法——前置元素的装饰
    linear-gradient在实战项目中的灵活运用——position和size的深入理解
    算法之单向链表
    awk(二)
    awk(一)
    grep与正则表达式
    编程原理
    Shell-bash的基本特性
    DNS域名轮循业务监控
  • 原文地址:https://www.cnblogs.com/shiwenhu/p/9641817.html
Copyright © 2011-2022 走看看