您可以使用以下方式初始化应用程序组件set() http://www.yiiframework.com/doc-2.0/yii-di-servicelocator.html#set%28%29-detail通过应用程序对象可用的方法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' => ...
],
]);
然后照常使用它:
use Yii;
...
Yii::$app->mailer->...
如果您想对整个应用程序使用数据库中的相同配置,您可以在应用程序引导期间获取并应用此配置。
创建自定义类并将其放置在例如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
}
}
然后在配置中添加:
return [
[
'app\components\Bootstrap',
],
];
注意:
如果具有相同 ID 的组件定义已经存在,则会
被覆盖。
官方文档:
- 引导接口 http://www.yiiframework.com/doc-2.0/yii-base-bootstrapinterface.html
- Mailer http://www.yiiframework.com/doc-2.0/yii-swiftmailer-mailer.html