rdlowrey / auryn

IoC Dependency Injector
MIT License
723 stars 65 forks source link

Prepare vs Delegate #136

Closed designermonkey closed 1 year ago

designermonkey commented 8 years ago

I notice that the prepare method accepts the created instance and the injector, as it's parameters. The delegate method doesn't seem to accept anything (at least according to documented examples).

In using a class context for delegation, this isn't such a big deal, but would it not make more sense to provide the same style parameters, so in delegates case, the injector?

Danack commented 8 years ago

but would it not make more sense to provide the same style parameters, so in delegates case, the injector?

No.

Factory functions and methods should not be aware of the injector; they should be completely agnostic to which DIC is being used. And delegation is just using these factory functions/methods to create objects.

One thing you may not have been aware of is that the factory functions/methods have their dependencies instantiated and injected by Auryn. If you absolutely need to, you can use the injector as a ServiceLocator by sharing the injector.

$fn = function (Injector $injector) {
    // Service locator type code here.
};
$injector->share($injector);
$injector->delegate('FooInterface', $fn);
$injector->make('FooInterface');

However using a ServiceLocator is bad and wrong for the vast majority of cases.

The prepare functionality is different. It is an acknowledgement that sometimes it is not possible to bootstrap an application using clean OO code. Whatever function is used to prepare the class does not have it's parameters wire up and injected. Instead they are hard-coded to be the object that has just been instantiated and the injector.

It isn't great to have to need to do this, but sometimes it is necessary.

TL:DR Factories are real objects and are part of your actual application. They need to be unaware of what DI library is being used. Prepare functions are part of the bootstrap layer, and so don't need to be as clean.

designermonkey commented 8 years ago

Yeah, I get that about factories, and was unaware of the dependencies being injected, so that answers my question in another way.

I think the docs for this need updating to explain these things, as the code is so complicated to read through.

Thanks for the answer though.

kelunik commented 7 years ago

@designermonkey Could you provide a PR with your suggested documentation change?

Danack commented 1 year ago

Closing, as it seems clear to me, so no motivation to polish the words.