yii2 icon indicating copy to clipboard operation
yii2 copied to clipboard

How can I inject configured Application component into Model instance?

Open glagola opened this issue 10 years ago • 1 comments

Hi, I have a problem described in subject. Let me explain. I use basic application template. I have simple model Search, which uses application component GoogleCustomSearch for search through Google Custom Search API. GoogleCustomSearch has to be configured with Google API key and Search Engine ID. I specifying Google API key and Search Engine ID via application config config/web.php. I would like to inject configured instance of GoogleCustomSearch into an instance of the Search model. Is it possible to reach my goal in a cleaner way (workaround below)?

<?php

namespace app\models;

use app\components\GoogleCustomSearch;
use yii\base\Model;

class Search extends Model
{
    /** @var GoogleCustomSearch */
    protected $googleCustomSearch;

    public function __construct(GoogleCustomSearch $googleCustomSearch, array $config = [])
    {
        $this->googleCustomSearch = $googleCustomSearch;
        parent::__construct($config);
    }
    ....
}
<?php

namespace app\components;

use yii\base\Component;
use yii\base\InvalidValueException;

class GoogleCustomSearch extends Component
{
    public $searchEngineId;
    public $apiKey;
    ...
}

My current workaround below

<?php
// File: config/bootstrap.php

use app\models\Search;
use yii\di\Container;
use yii\web\Application;

\Yii::$container->set('search', function (Container $container, $params, $config) {
    $googleCustomSearch = $container->get(Application::class)->googleCustomSearch;
    array_unshift($params, $googleCustomSearch);
    return $container->get(Search::class, $params, $config);
});
<?php
// File: web/index.php

use yii\web\Application;

....

require (__DIR__ . '/../config/bootstrap.php');
$config = require(__DIR__ . '/../config/web.php');

\Yii::$container
    ->setSingleton(Application::class, [], [$config])
    ->get(Application::class)
    ->run()
;

And then call

/** @var Search $model */
$model = \Yii::createObject('search');

Is there cleaner way to inject configured component to an object instance?

Q A
Yii version 2.0.9
PHP version 7.0.10
Operating system Linux desktop 4.7.2-1-ARCH #1 SMP PREEMPT Sat Aug 20 23:02:56 CEST 2016 x86_64 GNU/Linux

glagola avatar Sep 10 '16 13:09 glagola

This is an automated comment, triggered by adding the label question.

Please note, that the GitHub Issue Tracker is for bug reports and feature requests only.

We are happy to help you on the support forum, on IRC (#yii on freenode), or Gitter.

Please use one of the above mentioned resources to discuss the problem. If the result of the discussion turns out that there really is a bug in the framework, feel free to come back and provide information on how to reproduce the issue. This issue will be closed for now.

yii-bot avatar Sep 10 '16 13:09 yii-bot