Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p><sub>I don't know where you leaned about the DI, but the resources seem quite questionable. Instead you should begin by watching <a href="http://www.youtube.com/watch?v=RlfLCWKxHJ0" rel="nofollow">this lecture</a>, followed by <a href="http://martinfowler.com/articles/injection.html" rel="nofollow">article</a> from <em>Martin Fowler</em>. Maybe supplemented by <a href="http://blog.ircmaxell.com/2013/01/dependency-injection-programming-with.html" rel="nofollow">this</a> short video.</sub></p> </blockquote> <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>This is not implementing dependency injection. It actually is just an example of poorly implemented static factory method (anti)pattern. Especially the magical methods <code>$photo-&gt;setConfig()</code> and <code>$photo-&gt;setResponse()</code> which apparently do some work, but receive no parameters.</p> <p>And then there is this code:</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>Instead of just assigning values, you decide to hide the dependencies of it, and, if they are not provided, to take them from global scope. And of course, your constructor ends up containing quite a log of computation. Thus making it untestable.</p> <p>Oh .. and then there is the magical boolean value. Whenever where is such a parameter assigned to a class in constructor, it is a clear sign that you actually needed two different classes, which implement same interface. </p> <p>So.. to answer your question:</p> <blockquote> <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> </blockquote> <p>No. Your example is not better. You just combined the worst parts from both your earlier code example in single class definition.</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