简体   繁体   中英

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)

$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:

 $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"

 $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,...);
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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