Yiiのconsoleコマンドからメール配信を行う方法

メール配信には、「Yiiでメール周りの設定をする」にも書きましたが、mailerというエクステンションを利用しています。
今回、consoleコマンドから、メールを送信しようとした場合、

  • Yii::app()->controllerは設定されていない。
  • renderPartialが使えない。

という問題に遭遇したので、対処方法を書いておきます。
修正するのはmailerエクステンションのEMailerクラスのgetView関数です。具体的には、

public function getView($view, $vars = array(), $layout = null)
{
   $body = Yii::app()->controller->renderPartial($this->pathViews.'.'.$view, array_merge($vars, array('content'=>$this->_myMailer)), true); 
   list($subject,$body)=explode("\n",$body,2);
   $this->_myMailer->Subject=$subject;
   if ($layout === null) {
      $this->_myMailer->Body = $body;
   }
   else {
      $this->_myMailer->Body = Yii::app()->controller->renderPartial($this->pathLayouts.'.'.$layout, array_merge($vars, array('content'=>$body)), true);
   }
}

public function getView($view, $vars = array(), $layout = null)
{
  //Yii::app()->controllerが設定されているかチェック
  //設定されてなければsiteコントローラをコントローラとして利用
  $controller=Yii::app()->controller;
  if(!$controller)
    $controller = new CController('site');

  //renderPartialのかわりにrenderInternalを利用
  $body = $controller->renderInternal(YiiBase::getPathOfAlias($this->pathViews.'.'.$view).'.php', array_merge($vars, array('content'=>$this->_myMailer)), true);
  list($subject,$body)=explode("\n",$body,2);
  $this->_myMailer->Subject=$subject;
  if ($layout === null) {
    $this->_myMailer->Body = $body;
  }
  else {
    $this->_myMailer->Body = $controller->renderInternal(YiiBase::getPathOfAlias($this->pathLayouts.'.'.$layout).'.php', array_merge($vars, array('content'=>$body)), true);
  }
}

のようにしたらOKです。

ちょっと解説しておきます。
まず、Yii::app()->controllerが設定されているかチェックして、設定されていないようなら、siteコントローラを利用することにします。(siteコントローラでなくても構いません)

次にrenderPartialですが、

CConsoleApplication does not have a method named "getTheme"

のようなエラーが出るので、かわりにrenderInternalを利用します。
ただし、renderInternalは、viewファイルの設定をフルパスでする必要があるので、

YiiBase::getPathOfAlias($this->pathViews.'.'.$view).'.php'

のようにYiiBase::getPathOfAlias関数を利用して、「$this->pathViews.’.’.$view」をYiiのパスエイリアスからフルパスに変換し、最後にファイルのエクステンションである「.php」を付加するようにします。

投稿日:
カテゴリー: php タグ: