Inject dependencies in controllers instead of calling Yii::$app

Hello forum,

I’m starting a new project using Yii 2 (since Yii 3 is not yet finished when it comes to ActiveRecord etc), and was wondering if it’s possible to inject dependencies in the controller classes instead of calling the global Yii::$app variable? E.g. for Yii::$app->user.

Or maybe it’s better to use Yii 3 and then pull other ORM packages as an alternative to those yet not finished?

if it’s possible to inject dependencies in the controller classes instead of calling the global Yii::$app variable?

Yes. It’s definitely possible. See official guide.

Or maybe it’s better to use Yii 3 and then pull other ORM packages as an alternative to those yet not finished?

You can try Cycle ORM or Doctrine while AR is being developed. Or stick to yiisoft/db only.

2 Likes

What do you need in AR that is not yet working?
I have not tried yet everything but it should work on basics needed most of the time

If you insist with Yii2 @terabytesoftw have written excellent tutorial on that. I hope he puts it in something accessible like a forum post or a blog post.

Here it is: