Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing the DI container
    text
    copied!<p>I'm starting a new project and setting up the base to work on. A few questions have risen and I'll probably be asking quite a few in here, hopefully I'll find some answers.</p> <p>First step is to handle dependencies for objects. I've decided to go with the dependency injection design pattern, to which I'm somewhat new, to handle all of this for the application.</p> <p>When actually coding it I came across a problem. If a class has multiple dependencies and you want to pass on multiple dependencies via the constructor (so that they cannot be changed after you instantiate the object).</p> <p>How do you do it without passing an array of dependencies, using call_user_func_array(), eval() or Reflection? This is what i'm looking for:</p> <pre><code>&lt;?php class DI { public function getClass($classname) { if(!$this-&gt;pool[$classname]) { # Load dependencies $deps = $this-&gt;loadDependencies($classname); # Here is where the magic should happen $instance = new $classname($dep1, $dep2, $dep3); # Add to pool $this-&gt;pool[$classname] = $instance; return $instance; } else { return $this-&gt;pool[$classname]; } } } </code></pre> <p>Again, I would like to avoid the most costly methods to call the class. Any other suggestions?</p> <p>Also, how do I access the DI class inside classes, for example, in controllers that need to access different models? Should I call it statically or pass it along each class that would require it? I don't think the last idea is feasible.</p> <p>Thanks everyone.</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