使用数据库中的配置初始化应用程序组件 [英] Init application component with config from database
问题描述
我正在构建一个Yii2应用程序,该应用程序通过 swiftmailer扩展发送电子邮件.我将电子邮件设置(smtp,ssl,用户名等)存储在数据库表中,以便能够通过适当的视图对其进行编辑. 如何通过db表中的config初始化swiftmailer?
I'm building a Yii2 application that sends email through the swiftmailer extension. I store the email settings (smtp, ssl, username, etc..) in a database table, to be able to edit them with an apposite view. How can I init swiftmailer with config from the db table?
谢谢.
推荐答案
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' => ...
],
]);
然后照常使用它:
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.
创建自定义类并将其放置在例如app/components
;
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',
],
];
请注意:
如果已经存在具有相同ID的组件定义,则它将为 覆盖.
If a component definition with the same ID already exists, it will be overwritten.
官方文档:
- BootstrapInterface
- Mailer
这篇关于使用数据库中的配置初始化应用程序组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!