[英]Dependency Injection - Static Functions
我得到了依賴注入(例如數據庫)背后的基本思想,但我無法弄清楚如何將它與靜態函數一起使用:
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,...);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.