You can initialize application components using set() method available through application object Yii::$app
:
use Yii;
...
// Get config from db here
Yii::$app->set('mailer', [
'class' => 'yii\swiftmailer\Mailer',
'transport' => [
'class' => 'Swift_SmtpTransport',
// Values from db
'host' => ...
'username' => ...
'password' => ...
'port' => ...
'encryption' => ...
],
]);
Then use it as usual:
use Yii;
...
Yii::$app->mailer->...
If you want to use the same configuration from database for the whole application, you can get and apply this config during application bootstrap.
Create custom class and place it for example in app/components
;
namespace app\components;
use yii\base\BootstrapInterface;
class Bootstrap implements BootstrapInterface
{
public function bootstrap($app)
{
// Put the code above here but replace Yii::$app with $app
}
}
Then add this in config:
return [
[
'app\components\Bootstrap',
],
];
Note that:
If a component definition with the same ID already exists, it will be
overwritten.
Official documentation: