繁体   English   中英

依赖注入 - 静态函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM