Using DI to invoke events

Why is the DI Container not used when invoking events?

In your components and event classes you call call_user_func($handler[0], $event);
Wouldn’t it make sense to do Yii::$container->invoke() instead in order to inject dependencies?
What is the reason behind this?
I would just like to know if I miss something or if that’s a no-go in terms of structuring

What do you want to achieve by using Yii::$container->invoke()? Injection of dependencies into event handler?

Yeah I thought so.
There are dependencies that I only require in certain events. When they are passed there I don’t need to inject them into the constructor of my classes. Otherwise I need to call the invoke method in the event handler and build a wrapper just in order to pass a service or something like that.

I’m still trying to reduce the usage of the service locator. Usually I would just grab the required services via Yii::$app so I’m searching for good methods to replace it without having too many parameters in my constructor.
How would you do that?
Let’s say after a record is saved I want to send a mail to certain users. (I know how to write the code for that, it’s just about resolving the dependencies for the yii/web/View, a mailer component and maybe 1/2 others without calling Yii::$app and without having all of those in the constructor of the class where Event::on is called.
Of course I could create a single class for each event but that seems a little bit over the top to have about 50+ classes for each event

I’m afraid, declaring dependencies in constructor is the way to go when using DI. If there are too many, the component/service is doing too much and should be split.

That sounds about right. That’s not a good idea for a class to handler multiple unrelated events with different dependency set.

1 Like

As for DI in event handler, yes, we can do it with the help of container invoke. I see nothing bad or breaking in it. A pull request would be handy.