依赖注入 - 静态函数

时间:2013-10-15 07:05:09

标签: php static dependency-injection

我得到了依赖注入(例如数据库)背后的基本思想,但我无法弄清楚如何将它与静态函数一起使用:

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?

1 个答案:

答案 0 :(得分:1)

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

class Foo{
     ...
     public static function Get_By_ID($db,$id)
     {
        return new Foo($db,$id,$class_variables,...);
     }
相关问题