Note that there are some explanatory texts on larger screens.

plurals
  1. POunit testing with DI
    text
    copied!<p>I have a question concerning dependency injection. I have been keeping it simple so far, my methodology is basically to factor out object creation within objects and passing it instead in the constructer. I have come to a point where I am attacking larger classes that require multiple oblects. Some even have objects that contain other objects, with merry little singletons here and there. It gets ugly fast when testing these classes, as they are far from 'isolated' they are still hard-coded to their dependencies.</p> <p>So. Injecting an object or 2 for a trivial class is straightforward, </p> <p>I have looked into dependency containers, saw many implementations and am now wondering what is the advantage of using container vs. a registry for example. Couldn't one just as easily use a registry to hold anonymous functions that create the needed dependencies when called upon? </p> <p>The 2 containers I peeked into, <a href="http://www.potstuck.com/" rel="nofollow">Php Dependency</a> and <a href="https://github.com/fabpot/Pimple" rel="nofollow">Pimple</a> differ greatly in the implementation. </p> <p>I am wondering on the advantages of user a container vs. passing straight objects. I fail to understand how php-dependency's implementation would be tested, ie how would one implement the mock database object in phpunit without the actual class being injected when tested? Is there advantage to having dependency mapped out and used in doctags like this?</p> <pre><code>Class Book { private $_database; /** * @PdInject database */ public function setDatabase($database) { $this-&gt;_database = $database; } } </code></pre> <p>Pimple, on the other hand takes a totally different approach. No docblock tags, no mapping in seperate file, it seems like some kind of souped up registry ....</p> <pre><code> Objects are defined by anonymous functions that return an instance of the object: // define some parameters $container['cookie_name'] = 'SESSION_ID'; $container['session_storage_class'] = 'SessionStorage'; </code></pre> <p>... that can behave as a factory at same time:</p> <pre><code>$container['session'] = function ($c) { return new Session($c['session_storage']); }; </code></pre> <p>Declaring shared ressources always serves the same instance (singleton!?):</p> <pre><code>$c['session'] = $c-&gt;share(function ($c) { return new Session($c['session_storage']); }); </code></pre> <p>This is were I got the idea of using a simple registry that holds either objects or anonymous functions. BUt am I missing something in this approach? Pimple, I can see to how to test, but Php-Dependency is unclear to me from a testing point of view.</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