auryn icon indicating copy to clipboard operation
auryn copied to clipboard

Prepare vs Delegate

Open designermonkey opened this issue 9 years ago • 3 comments

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?

designermonkey avatar Feb 01 '16 15:02 designermonkey

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.

Danack avatar Feb 25 '16 14:02 Danack

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.

designermonkey avatar Feb 25 '16 15:02 designermonkey

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

kelunik avatar Jan 09 '17 11:01 kelunik

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

Danack avatar Apr 17 '23 13:04 Danack