使用数据库中的配置初始化应用程序组件


Init application component with config from database

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

谢谢。

您可以使用应用程序对象Yii::$app提供的 set() 方法初始化应用程序组件:

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 的组件定义,它将 覆盖。

官方文档:

  • 引导接口
  • 邮件

感谢并@arogachev他的回答,这给了我一个想法,我解决了问题。 我发布这个是为了帮助任何人

我在 Mailer 中解决了修改 swiftmailer 组件的问题.php添加了以下内容:

use app'models'Administracion; //The model i needed for access bd
 class Mailer extends BaseMailer
{
...
...
//this parameter is for the config (web.php)
public $CustomMailerConfig = false;
...
...
...
/**
     * Creates Swift mailer instance.
     * @return 'Swift_Mailer mailer instance.
     */
    protected function createSwiftMailer()
    {
        if ($this->CustomMailerConfig) {
            $model = new Administracion();
            $this->setTransport([
                'class' => 'Swift_SmtpTransport',
                'host' => $model->getSmtpHost(),
                'username' => $model->getSmtpUser(),
                'password' => $model->getSmtpPass(),
                'port' => $model->getSmtpPort(),
                'encryption' => $model->getSmtpEncryption(),
            ]);
        }
        return 'Swift_Mailer::newInstance($this->getTransport());
    }

Web中.php添加了以下内容:

'mailer' => [ 
            'class' => 'yii'swiftmailer'Mailer',
            'enableSwiftMailerLogging' =>true,
            'CustomMailerConfig' => true, //if its true use the bd config else set the transport here
            'useFileTransport' => false,
],