gpt4 book ai didi

php - 依赖注入(inject)——静态函数

转载 作者:搜寻专家 更新时间:2023-10-31 21:36:02 25 4
gpt4 key购买 nike

我了解了依赖注入(inject)背后的基本思想(例如对于数据库),但我不知道如何将它与静态函数一起使用:

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);

我错过了什么?

(附加 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,...);
}

关于php - 依赖注入(inject)——静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19375147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com