PHP Dependency Injection

前端 未结 4 1339
一个人的身影
一个人的身影 2020-11-29 05:42

I\'m trying to get my head around Dependency Injection and I understand it, for the most part.

However, say if, for some reason, one of my classes was dependent on s

4条回答
  •  一个人的身影
    2020-11-29 06:11

    If you have several dependencies to deal with, then yes a DI container can be the solution.

    The DI container can be an object or array constructed of the various dependent object you need, which gets passed to the constructor and unpacked.

    Suppose you needed a config object, a database connection, and a client info object passed to each of your classes. You can create an array which holds them:

    // Assume each is created or accessed as a singleton, however needed...
    // This may be created globally at the top of your script, and passed into each newly
    // instantiated class
    $di_container = array(
      'config' = new Config(),
      'db' = new DB($user, $pass, $db, $whatever),
      'client' = new ClientInfo($clientid)
    );
    

    And your class constructors accept the DI container as a parameter:

    class SomeClass {
      private $config;
      private $db;
      private $client;
     
      public function __construct(&$di_container) {
        $this->config = $di_container['config'];
        $this->db = $di_container['db'];
        $this->client = $di_container['client'];
      }
    }
    

    Instead of an array as I did above (which is simple), you might also create the DI container as an class itself and instantiate it with the component classes injected into it individually. One benefit to using an object instead of an array is that by default it will be passed by reference into the classes using it, while an array is passed by value (though objects inside the array are still references).

    Edit

    There are some ways in which an object is more flexible than an array, although more complicated to code initially.

    The container object may also create/instantiate the contained classes in its constructor as well (rather than creating them outside and passing them in). This can save you some coding on each script that uses it, as you only need to instantiate one object (which itself instantiates several others).

    Class DIContainer {
      public $config;
      public $db;
      public $client;
    
      // The DI container can build its own member objects
      public function __construct($params....) {
        $this->config = new Config();
    
        // These vars might be passed in the constructor, or could be constants, or something else
        $this->db = new DB($user, $pass, $db, $whatever);
    
        // Same here -  the var may come from the constructor, $_SESSION, or somewhere else
        $this->client = new ClientInfo($clientid);
      }
    }
    

提交回复
热议问题