PHP依赖注入简单理解

adapter=new MySqlAdapter;
		}
		
		public function getList(){
			$this->adapter->query("sql语句");//使用MySslAdapter类中的query方法;
		}
	}
	class MySqlAdapter{};
	
	//我们可以通过依赖注入来重构上面这个例子
	
	class UseDataBase{
		protected $adapter;
		poublic function __construct(MySqlAdapter $adapter){
			$this->adapter=$adapter;
		}
		
		public function getList(){
			$this->adapter->query("sql语句");//使用MySslAdapter类中的query方法;
		}
	}
	class MySqlAdapter{};
	
	//但是,当我们有很多种数据库时,上面的这种方式就达不到要求或者要写很多个usedatabase类
	//所以我们再重构上面的这个例子
	class UseDataBase{
		protected $adapter;
		poublic function __construct(AdapterInterface $adapter){
			$this->adapter=$adapter;
		}
		
		public function getList(){
			$this->adapter->query("sql语句");//使用MySslAdapter类中的query方法;
		}
	}
	interface AdapterInterface{};
	class MySqlAdapter implements AdapterInterface{};
	class MSsqlAdapter implements AdapterInterface{};
	
	//这样的话,当要使用不同的数据库时,我们只需要添加数据库类就够了,usedatabase类则不需要动。
?>

你可能感兴趣的:(php基础)