使用数据库配置的Init应用程序组件

Ale*_*t83 2 php initialization swiftmailer yii2

我正在构建一个通过swiftmailer扩展程序发送电子邮件的Yii2应用程序.我将电子邮件设置(smtp,ssl,username等)存储在数据库表中,以便能够使用适当的视图对其进行编辑.如何从db表中使用config启动swiftmailer?

谢谢.

aro*_*hev 11

您可以使用通过应用程序对象提供的set()方法初始化应用程序组件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' => ...
    ],
]);
Run Code Online (Sandbox Code Playgroud)

然后像往常一样使用它:

use Yii;

...

Yii::$app->mailer->...
Run Code Online (Sandbox Code Playgroud)

如果要对整个应用程序使用数据库中的相同配置,则可以在应用程序引导期间获取并应用此配置.

创建自定义类并将其放置在例如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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在config中添加:

return [
    [
        'app\components\Bootstrap',
    ],
];
Run Code Online (Sandbox Code Playgroud)

注意:

如果已存在具有相同ID的组件定义,则将覆盖该组件定义.

官方文件: