K
K
Kirill Tekord2017-03-25 22:49:12
Yii
Kirill Tekord, 2017-03-25 22:49:12

How to inject a component through Yii::$container into a class constructor?

There is a class which works with a DB. The database connection instance is passed through the constructor.

class UpdateStatsCommand extends Object {
  /**
   * @var Connection
   */
  protected $db;

  /**
   * @inheritdoc
   */
  public function __construct(Connection $db, array $config = []) {
    $this->db = $db;

    parent::__construct($config);
  }
    ...

Question : how to make it so that when this class is instantiated via Yii::createObject(UpdateStatsCommand::class), a reference to the db application component is injected into the constructor?
I tried adding the following to bootstrap.php:
Yii::$container->set(yii\db\Connection::class, function () {
  return Yii::$app->get('db');
});

But on startup, the application crashes from memory overflow:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted
This seems to be due to the fact that when initializing the db component, Yii finds the class name yii\db\Connection in the container and tries to call a function that refers to the component, and the component is not initialized, respectively, its initialization begins and everything loops.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question