Dependency injection and initialization of the obj

2019-08-04 00:18发布

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条回答
狗以群分
2楼-- · 2019-08-04 00:45

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!?

查看更多
登录 后发表回答