• 简单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();
  • 相关阅读:
    Charles手机端抓包--证书
    新浪微盘批量下载
    [3140] Sublime Text 2.x, 3.x 通用注册码、密钥集合
    栈的数组实现
    栈的链表实现
    基数排序
    多项式相乘-数组实现
    最大子序列和问题的四种算法
    链表的实现
    时间同步算法与Simple Ring-based election algorithm算法分析-转载
  • 原文地址:https://www.cnblogs.com/shiwenhu/p/9641817.html
Copyright © 2020-2023  润新知