PHP Dependency Injection

前端 未结 4 1337
一个人的身影
一个人的身影 2020-11-29 05:42

I\'m trying to get my head around Dependency Injection and I understand it, for the most part.

However, say if, for some reason, one of my classes was dependent on s

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 06:22

    I recommend you to use Singltones or Mutlitones. In these cases you will be always able to get objects via static class' methods.

    The other way (couldn't find a correct pattern name, but it could be Registry) is to use one global static object to store multiple objects' instances. E.g. (simplified code, without any checks):

    class Registry {
        private static $instances = array();
    
        public static function add($k, $v) {
            $this->instances[$k] = $v;
        }
    
        public static function get($k) {
            return $this->instances[$k];
        }
    }
    
    class MyClass {
        public function __construct() {
            Registry::add('myclass', $this);
        }
    }
    

提交回复
热议问题