简体   繁体   中英

Dependency injection in PHP and DIC

I have a bone to pick with dependency injection. It seems like such a simple concept has led to a lot of confusion amongst many, and the 'right' way to it seems to spiral out of control in terms of complexity. In keeping things really simple I just want to know:

Is it good practice if I use standard functions to register my dependencies, like this:

function someObject() {
  return new someObject();
}

And can I pass parameters?

function someObject($param1) {
  return new someObject($param1);
}

Finally how about using a simple custom container class:

class Dependencies {
  function someObject($param1) {
    return new someObject($param1);
  }
}

And using it:

class SomeClass {
  public function __construct(Dependencies $dependencies) {
    $this->dependencies = $dependencies
  }

  public function methodNeedsDependency() {
    $param1 = 'one';
    $task = $this->dependencies->someObject($param1);
  }
}

I guess what I'm asking is, is this a decent attempt at a very simple implementation of a DIC? Or are there some underlying major issues bubbling under the surface?

Thanks!

If SomeClass is a factory, designed to create some instance with some exact config given, then yes, we could say this is very simple implementation of DIC.

Issues here? Well, let's say You want to create someObject with other constructor params.

Solutions:

  1. Create another SomeClass factory that will pass other params. It's redundant solution that also mixes two application layers ( config with object creation layer ).

  2. Parametrize methodNeedsDependency with params that will be passed to someObject . It's something that allows You to postpone in code config creation.

  3. and last but the most proper way: DIC should be flexible, should allow You to create any service instances with any dependencies, and all of configuration should be stored in configuration layer. Separation of concerns - try to make DIC unaware of what object type is creating. Just let him make objects that You described somewhere else.

There are a lot of other issues also, like for example what if You would like to have only one instance of given class for whole DIC ( it's easy to "if" it, but that's another workaround to proper solution ) or what with circular references.

This discussion can go on and on with other issues about architecture in general, like "services should be stateless" what makes it unnecesary to have more then one, but answer to your question are those 3 points. Of course remember it's not ultimate-mega-hiper answer for DIC. It's just my way of seeing it ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM