douza19870617 2015-01-29 16:15
浏览 41
已采纳

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

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?

Thank you.

  • 写回答

2条回答 默认 最新

  • duanhuren5581 2015-01-29 17:36
    关注

    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' => ...
        ],
    ]);
    

    Then use it as usual:

    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.

    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',
        ],
    ];
    

    Note that:

    If a component definition with the same ID already exists, it will be overwritten.

    Official documentation:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器