阿神2017-04-11 10:01:533楼
依赖注入是面向对象编程里面用来解耦的设计模式.
class db {
public static function get_db() {
return new mysqli('127.0.0.1','user','pass','dbname',3306);
}
}
class post {
private $db;
public function set_db($db){
$this->db = $db;
}
public function get_post($id){
return $this->db->query('SELECT * FROM post WHERE id ='.intval($id))->fetch_all();
}
}
$post = new post();
$post->set_db( db::get_db() ); //注入post类依赖的数据库连接对象,通过类名直接调用静态方法get_db
$post->get_post(1024);
对比下过程式的写法:
function db() {
static $db; //静态变量避免重复连接
if ($db) {
return $db;
} else {
$db = new mysqli('127.0.0.1','user','pass','dbname',3306);
return $db;
}
}
function get_post_v1($db, $id) {
return $db->query('SELECT * FROM post WHERE id ='.intval($id))->fetch_all();
}
get_post_v1(db(), 1024); //调用函数时注入依赖
function get_post_v2($id) {
$db = db(); //在函数内部包含依赖(耦合?不见得)
return $db->query('SELECT * FROM post WHERE id ='.intval($id))->fetch_all();
}
get_post_v2(1024);
$app['db'] = db(); //应用全局数组,Windows系统里的注册表?你的应用比Windows还复杂?
function get_post_v3($id) {
global $app; //全局变量
return $app['db']->query('SELECT * FROM post WHERE id ='.intval($id))->fetch_all();
}
get_post_v3(1024);