我了解了依赖嵌入背后的基本思想(例如用于数据库),但我无法弄清楚如何将其与静态函数一起使用:
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);
只能使用保存在(私有$db)中的"$db"创建新对象
$b = $f->Create_Bar();
你怎么能解决这个问题?是唯一的方法:
$b = $f->Create_Bar($db_for_bar);
附加:如何使用静态函数来做到这一点?
$b = Foo::Create_Bar($db_for_foo,$db_for_bar);
我错过了什么?
(附加 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
但是,如果在"Foo"内部称为"Create_Bar"怎么办
$this->Create_Bar(???) //Where does the $db_for_bar come from?
)
这
是一个很好的解决方案,我不明白你为什么说它不起作用:
class Foo{
...
public static function Get_By_ID($db,$id)
{
return new Foo($db,$id,$class_variables,...);
}