3

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

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?

)

4

1 回答 1

1

这是一个很好的解决方案,我不明白你为什么说它不起作用:

class Foo{
     ...
     public static function Get_By_ID($db,$id)
     {
        return new Foo($db,$id,$class_variables,...);
     }
于 2013-10-15T07:49:09.360 回答