Depedency inside Controllers and other classes
What is the best practice to use a dependency (defined in config) ?
I'd expect to have it from constructor, but other parameters are passed in it.
class CustomController extends \yii\web\Controller
{
public function __construct(\yii\authclient\clients\GitHub $githubClient)
{
}
}
So I've solved using:
Yii::getApp()->container->get(\yii\authclient\clients\GitHub::class)
Is this last the right and suggested approach?
"Autowiring" is a phenomenon when dependencies can be automatically passed to the constructor or another method. It is a responsibility of a framework you're using, not DI container. I guess you're using Yii2 which don't know autowiring. I'm happy to say yii3 already has this feature. Hope we'll see a stable release of this major update this year :+1:
"Autowiring" is a phenomenon when dependencies can be automatically passed to the constructor or another method. It is a responsibility of a framework you're using, not DI container. I guess you're using Yii2 which don't know autowiring.
I refer to Yii3. My question is about what is the recommendation.
@rob006 What do you think?
@FabrizioCaldarelli sorry, didn't see you're in YiiSoft team. I thought you're just one more newbie, shame on me.
It is a responsibility of a framework you're using, not DI container
Either I'm wrong or it's just not about this DI container. It is really responsible for autowiring. Diving deeper into the code...
As I see a web request results into a controller action through \yii\base\Module::createControllerByID which calls $this->app->createObject. So, the controller must be created within the DI container which resolves your dependencies.
I think you need to provide a bit more code to debug.
I think you just need to keep your controller's parent declaration in your mind: public function __construct($id, $module). Try to write so and make your dependency to be the third parameter.
@viktorprogger is right. You should have something like this:
public function __construct($id, $module, \yii\authclient\clients\GitHub $githubClient)
{
parent::__construct($id, $modjule);
$this->githubClient = $githubClient;
}
Ok, but is there a shared solution that we can suggest? Just to have the same approach everywhere in the code.
I indeed don't like some of this and some of that in the code.
Yes. That's what was mentioned somewhere as "wider use of DI". But, you are right, it should be stressed out stronger.