我理解了依赖注入的基本概念(例如用于数据库),但我无法想象如何在静态函数中使用它:
class Foo{
private $id;
private $class_variables,...;
private $db;
public function __construct($db,$id,$class_varibles,...)
{
$this->db=$db;
//Assignments
}
public static function Get_By_ID($id)
{
//No DB-Connection here
return new Foo(?);
}
}
这样做的唯一方法是以下方式吗?
class Foo{
...
public static function Get_By_ID($db,$id)
{
//Do work here!
return new Foo($db,$id,$class_variables,...);
}
对于几个静态函数而言,这似乎是很多额外的工作。
此外:
$f = new Foo($db);
只能使用已保存在(private $db)中的"$db"来创建新对象。
$b = $f->Create_Bar();
您如何解决这个问题?唯一的方法是:
$b = $f->Create_Bar($db_for_bar);
附加说明:如何使用静态函数实现此操作?
$b = Foo::Create_Bar($db_for_foo,$db_for_bar);
What am I missing?
(Additional 2:
$f = new Foo($db); //Dependency Injection ($db is saved in $f, and is the database-link for example)
$f->Create_Bar($db_for_bar); //OK - No Problem
但如果“Create_Bar”在“Foo”内部调用呢?
$this->Create_Bar(???) //Where does the $db_for_bar come from?
)