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

时间:2015-01-29 16:15:13

标签: php initialization yii2 swiftmailer

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

谢谢。

2 个答案:

答案 0 :(得分:11)

您可以使用应用程序对象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
    }
}

然后在config中添加:

return [
    [
        'app\components\Bootstrap',
    ],
];

请注意:

  

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

官方文件:

答案 1 :(得分:0)

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

我解决了modyfing swiftmailer组件的问题,在 Mailer.php 中添加了这个:

Prelude> let foo = (1+2, 3+4) :: (Int, Int)
Prelude> :print foo
foo = ((_t3::Int),(_t4::Int))
Prelude> fst foo
3
Prelude> :print foo
foo = (3,(_t5::Int))
Prelude> snd foo
7
Prelude> :print foo
foo = (3,7)

Web.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());
    }