Dependency injection and initialization of the object

爷,独闯天下 提交于 2019-12-24 07:30:48

问题


I am quite a newbie to decent OOP and DI, thus was wondering, if the following example and its pattern of initialization of my bootstrap class, that includes dependent objects, is really alright to use, e.g.:

new Session(
   new Config, 
   new Database ( 
       new Config 
   ), 
   new Page ( 
       new Config 
   ), 
   new Statistics ( 
      new Database ( 
         new Config 
      ) 
   ), 
   new Notification, 
   new Filter
);

I believe, those which familiar with DI could say something about the piece of code above in bootstrap object?

It looks a bit bulky but is this alright? Is this the way, that we could call it alright/correct/acceptable?


回答1:


After some time of learning an investigating on the new issue, I have finally came to the conclusion, that for my case, the best Dependency Injection Container would be:

Dice - minimalist Dependency Injection Container for PHP.

It has only one file and in order to have the code, that's from my question be initialized, all you need is:

(new Dice)->create('Session');

Dice DIC will take care of the rest. You can read more about Dice on the Tom Butler (developer) home page.

I personally think that this is the best (shortest and easiest) way of injecting dependencies and should be inbuilt in PHP by default, and I actually wonder why it's not?


In order to decouple your code from the particular dependency injection container, I'd better recommend using a custom class wrapper:

class DIC extends Dice
  {
    function __construct( $component, array $args = array(), $callback = null, $forceNewInstance = false )
      {
          return parent::create( $component, $args, $callback = null, $forceNewInstance = false );
      }
  }

which will also help to shorten even more the initialization process, to something really unbelievably amazing.

Now, in order to instantiate the complicated sets of DIs, like:

new Session( new Config, new Database ( new Config ), new Page ( new Config ), new Statistics ( new Database ( new Config ) ), new Notification, new Filter );

All you have to do is:

new DIC('Session');

If you would want to pass a parameter to the constructor, you could go with:

new DIC('Session', array($param));

I don't know what others think but I find this amazing (at least so far, of where I am today).

Ask you please, be kind commenting about possible drawbacks, that I could face in the future using this DIC (Dice) or this method in general!?



来源:https://stackoverflow.com/questions/21368535/dependency-injection-and-initialization-of-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!