2015-09-10 67 views
0

即時通訊使用Yii2,我想配置郵件參數geting從數據分貝。從模型配置郵件參數 - Yii2

例子:

'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不能調用從模型的方法,我試過,但拋出一個錯誤

+0

可能重複的[初始化應用組件與數據庫配置](http://stackoverflow.com/questions/28219440/init-application-component-with-config-from-database) – arogachev

回答

1

感謝@ Onedev.Link和@arogachev他answer.that給了我一個想法,我解決問題。

我解決問題modyfing 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, 
], 
2

的Yii從這個配置初始化程序。在yii2運行之前,你不能使用yii2。

$application = new yii\web\Application($config); 

作爲替代方案,您可以配置郵件創建這樣的bootstrap.php文件申請後:Yii::$app->set('mailer', (new MailerConfigurator())->getConfig());

+0

我試過這個http://stackoverflow.com/questio ns/28219440/init-application-component-with-config-from-database在控制器中,但是在哪裏調用我創建的函數來啓動應用程序? – Cocuba

+0

這是正確的答案。 'Yii :: $ app-> set()'沒有啓動新的應用程序,只是改變[ServiceLocator]的組件(http://www.yiiframework.com/doc-2.0/guide-concept-service-locator.html) 。 –

+0

謝謝你的回答,給了我一個主意,請看下面@ Onedev.Link – Cocuba