Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You shouldn't use <code>static</code> here at all. Just create a container: <code>$container = new DIContainer();</code> and use that object as a typical dependency. After all there's a very few places in the core of application that require access to the whole container.</p> <p>Take a look at <a href="https://github.com/symfony/DependencyInjection">Symfony's Dependency Injection component</a> - piece of quite good code.</p> <hr> <h3>EDIT:</h3> <p>According to the first comment. Yes, you've misunderstood me. Usually you'd need only several dependencies from the container, so you'll write something like:</p> <pre><code>$service = new Service($container-&gt;get('dep.a'), $container-&gt;get('dep.b'), 123); </code></pre> <p>My point was that you shouldn't use static property within the container, as it makes it nothing more but a global object. There would be no difference between:</p> <pre><code>global $container; $widget = new Widget($container-&gt;fetch('widgetDep')); $kumquat = new Kumquat($container-&gt;fetch('kumquatDep')); $widget = new Widget(Container::getInstance()-&gt;fetch('widgetDep')); $kumquat = new Kumquat(Container::getInstance()-&gt;fetch('kumquatDep')); // You're using new objects but they share the same, **global** array. // Therefore, they are actually global themselves. $widget = new Widget((new Container())-&gt;fetch('widgetDep')); $kumquat = new Kumquat((new Container())-&gt;fetch('kumquatDep')); </code></pre> <p>In other words, the Container itself should be a local variable, and if you'll need to access it somewhere else (some objects might need access to the entire container) then you should explicitly pass it as dependency to that object.</p> <p>As I said before, take a look at Symfony DIC and the whole framework to see how to make a good, well-written DIC.</p> <hr> <p>Simple container:</p> <pre><code>class Container { private $services = array(); public function get($service) { if (!array_key_exists($this-&gt;services, $service)) { throw ...; } return $this-&gt;services[$service]; } } $containerA = new Container(); $containerB = new Container(); // $containerA and $containerB are completely different // objects and don't share anything </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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