从型号Yii2配置邮件程序参数


Config mailer parameters from model - Yii2

im使用Yii2,我想配置从数据库获取数据的mailer参数。

示例:

'mailer' => [ 
            'class' => 'yii'swiftmailer'Mailer',
            'enableSwiftMailerLogging' =>true,
            'useFileTransport' => false,
            'transport' => [
                'class' => 'Swift_SmtpTransport',
                'host' => $model->getSmtpHost(),
                'username' => $model->getSmtpUser(),
                'password' => $model->getSmtpPass(),
                'port' => $model->getSmtpPort(),
                'encryption' => $model->getSmtpEncryption(),
            ],
        ]

但是从web.php无法调用模型中的方法,我尝试过,但抛出了一个错误

Yii从该配置初始化了应用程序。在运行yii2之前,您不能使用yii2。
$application = new yii'web'Application($config);

作为替代方案,您可以在bootstrap.php文件中创建应用程序后配置mailer,如下所示:Yii::$app->set('mailer', (new MailerConfigurator())->getConfig());

感谢@Onedev.Link和@arogachev的回答。这给了我一个想法,我解决了问题。

我解决了修改swiftmailer组件的问题,在Mailer.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,
],