简体   繁体   English

依赖注入 - 静态函数

[英]Dependency Injection - Static Functions

I get the basic idea behind Dependency Incjection (eg for Databases), but i couldn't figure out how to use it with 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(?);
    }
}

Is the only way to do this the following? 以下是唯一的方法吗?

class Foo{
     ...
     public static function Get_By_ID($db,$id)
     {
        //Do work here!
        return new Foo($db,$id,$class_variables,...);
     }

It seems like a lot of additional work for several static functions. 对于几个静态函数来说,似乎还有许多额外的工作。 Also: 也:

$f = new Foo($db);

will only be able to create new Objects with the "$db" it has saved in (private $db) 将只能使用保存在“私有$ db”中的“$ db”创建新对象

$b = $f->Create_Bar();

How can you solve this problem? 你怎么解决这个问题? Is the only way: 是唯一的方法:

$b = $f->Create_Bar($db_for_bar);

Additional: How to do it with an static function? 附加:如何使用静态功能?

$b = Foo::Create_Bar($db_for_foo,$db_for_bar);

What am I missing? 我错过了什么?

(Additional 2: (附加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

but what if "Create_Bar" is called inside "Foo" 但是如果在“Foo”里面调用“Create_Bar”怎么办?

 $this->Create_Bar(???) //Where does the $db_for_bar come from?

)

This is a good solution, I don't understand why you say it doesn't work: 这是一个很好的解决方案,我不明白为什么你说它不起作用:

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