Note that there are some explanatory texts on larger screens.

plurals
  1. PODependency Injection Confusion
    text
    copied!<p>I've been reading about Dependency Injection but the examples I've found just look like bad code to me, so my main question is am I right in thinking it is bad code, or am I misunderstanding the purpose of it, and is my example any better?</p> <pre><code>class Photo { protected $db; public function __construct() { $this-&gt;db = DB::getInstance(); } } </code></pre> <p>So this is bad code, and the suggestion of Dependency Injection, due to the multitude of setters that might be created if we explicitly set every variable, is:</p> <pre><code>class Container { protected $db; public static newPhoto() { $photo = new Photo; $photo-&gt;setDB(static::$db); $photo-&gt;setConfig(); $photo-&gt;setResponse(); return $photo; } } $photo = Container::newPhoto(); </code></pre> <p>But correct me if I'm wrong, we've just built a class whose sole responsibility it is to build another class, seems quite pointless, and we are using static methods which is apparently a very bad idea.</p> <p>The one benefit that I do see, which surprisingly to me isn't mentioned is that we can now test the Photo class independently by using the setters, whilst in the first example we couldn't.</p> <p>Something like this makes more sense to me:</p> <pre><code>class Photo { protected $db; protected $config; protected $response; public function __construct($dbConn=null,$config='123',$response=true) { if(is_null($dbConn)) $this-&gt;db = DB::getInstance(); else $this-&gt;db = $dbConn; ...etc } } $photo = new Photo($dbConn); </code></pre> <p>The class builds itself, there is no need for the static method to actually be called, the class can be tested with dummy data if values are used otherwise it falls back on defaults (which seems to be the only point of the Container class), and the dependencies are still somewhat obvious as opposed to the Container.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload