Simple example on how to use injector and DI?

As a DI noob, I wonder if there’s a simple example on how to use Yii 3 DI and injector?

As an example, say I have:

class ProcessOrderCommand
{
  public function __construct(Db $db, Curl $curl) { ... }
  public function run() { ... }
}

Which code would I have to call to automatically populate the $db and $curl variables with the correct classes?

Do I have to use DbInterface rather than Db, or is that just a considered best practice?

This simple snippet seems to do the trick:

<?php

require_once("vendor/autoload.php");

use Yiisoft\Di\Container;
use Yiisoft\Di\ContainerConfig;
use Yiisoft\Injector\Injector;

class ProcessOrderCommand
{
    public function __construct(Db $db, Curl $curl) {}
}

class Db {}
class Curl {}

$config    = ContainerConfig::create();
$container = new Container($config);
$injector  = new Injector($container);
$obj       = $injector->make(ProcessOrderCommand::class);

Will try to combine this with the most basic Route snippet I can figure out, too.

Do I have to use DbInterface rather than Db , or is that just a considered best practice?

In order to answer this for your case, check the following topics:

I think “code to an interface, not an implementation” is the one, eh? :slight_smile: On the other hand, sometimes the probability of switching the implementation is very, very low, so adding another layer of complexity might not be worth it. Not that an interface is so complicated…

PHPUnit should easily be able to do mocking of classes too, not only interfaces, IIRC.

Also might be useful:

1 Like