0

As per the authors of a large proportion of questions related to this (and many other) subjects on SO, I have done a LOT of reading around the subject of Dependency Injection. Whilst I understand the concept, and the basic usage, I am struggling to get over the line with the implementation of a Container class to manage dependencies.

Some example code - found here http://code.tutsplus.com/tutorials/dependency-injection-huh--net-26903

Container

// Also frequently called "Container"
class IoC {
    /**
     * @var PDO The connection to the database
     */
    protected $db;

    /**
     * Create a new instance of Photo and set dependencies.
     */
    public static newPhoto()
    {
        $photo = new Photo;
        $photo->setDB(static::$db);
        // $photo->setConfig();
        // $photo->setResponse();

        return $photo;
    }
}

$photo = IoC::newPhoto();

My question is regarding the passing of static::$db to the SetDB() method of the photo class - is static referring to the property of the container (IoC) class or referencing the property in the photo class?

The SetDB() method of the Photo class

protected $db
 public function setDB($dbConn)
{
    $this->db = $dbConn;
}

It may help to look at the link I listed above, as perhaps it is a case of the classes containing methods/properties that are not shown but assumed. I just cannot fathom how passing static::$db is doing anything - the $db property in the IoC class seems to have not been assigned a value.

When I create a custom example of this code - I (unsurprisingly) get an error saying I am not passing anything to the SetDB method.

I hope this is a clear enough question - I have spent the last couple of days getting myself tied in knots over DI, but it is starting to click but could do with a little shove!

Thanks in advance.

DJC
  • 1,175
  • 1
  • 15
  • 39
  • 2
    Have you read this? http://php.net/manual/en/language.oop5.late-static-bindings.php. Specifically `Late static bindings tries to solve that limitation by introducing a keyword that references the class that was initially called at runtime.` It seems their code is incomplete IMO. – honerlawd Jul 22 '15 at 20:50
  • OK i see so it is referencing the variable in the photo class, correct? But where is the $db database object actually created?? – DJC Jul 22 '15 at 20:52
  • 1
    Probably at some point that is not shown in his code. – honerlawd Jul 22 '15 at 20:55
  • do you mean the code in the link? – DJC Jul 22 '15 at 21:01
  • Yes, the code in the link is incomplete. – honerlawd Jul 23 '15 at 02:04
  • where would you imagine the db connection is created/passed to the others then? – DJC Jul 23 '15 at 07:05
  • Possible duplicate of [Service Locator, Dependency Injection (and Container) and Inversion of Control](http://stackoverflow.com/questions/10049940/service-locator-dependency-injection-and-container-and-inversion-of-control) – Paul Sweatte Dec 20 '16 at 16:46

0 Answers0