スマホかガラケーかPCか、でテンプレートを切り替える

symfony1.4のお話。
sfPHPViewを継承したクラスに切り替え処理実装。

ソース

  • 端末判定クラス(フィルターじゃなくてもいいが…)

class myMobileFilter extends sfFilter
{

 // ユーザーエージェント
 private $ua;

 function __construct()
 {
  $this->ua = $_SERVER['HTTP_USER_AGENT'];
 }

 public function execute($filterChain)
 {
  $filterChain->execute();
 }


 public function isTouch()
 {
  return (preg_match('/iPhone/', $this->ua) || preg_match('/Android/', $this->ua));
 }

 public function isDocomo()
 {
  return (preg_match('/DoCoMo/', $this->ua));
 }

 public function isAu()
 {
  return (preg_match('/UP\.Brower/', $this->ua) || preg_match('/KDDI-/', $this->ua));
 }

 public function isSoftbank()
 {
  return (preg_match('/J-PHONE/', $this->ua) || preg_match('/Vodafone/', $this->ua) || preg_match('/SoftBank/', $this->ua));
 }

 public function isWillcom()
 {
  return (preg_match('/WILLCOM/', $this->ua));
 }
 public function isEmobile()
 {
  return (preg_match('/emobile/', $this->ua));
 }

 /**
  * ガラケーかどうかを判定
  */
 public function isFeature()
 {
  return ($this->isDocomo() ||
      $this->isAu() ||
      $this->isSoftbank() ||
      $this->isWillcom() ||
      $this->isEmobile()
      );
 }
}

  • Viewクラス

getTemplateDir($moduleName, $this->getTemplate())
  . DIRECTORY_SEPARATOR
  . $actionName . $touchViewName . $this->getExtension();
  // ガラケー用のテンプレートファイルパス
  $featureTemplatePath = $config->getTemplateDir($moduleName, $this->getTemplate())
  . DIRECTORY_SEPARATOR
  . $actionName . $featureViewName . $this->getExtension();

  // スマートフォンからのアクセスでかつテンプレートが存在する場合
  if ($myMobileFilter->isTouch() && is_file($touchTemplatePath)) {
  parent::initialize($context, $moduleName, $actionName, $touchViewName);
  // ガラケーからのアクセスで、かつテンプレートが存在する場合
  } elseif ($myMobileFilter->isFeature() && is_file($featureTemplatePath)) {
  parent::initialize($context, $moduleName, $actionName, $featureViewName);
  // 上記のいずれにも当てはまらない場合はPC扱い
  } else {
  parent::initialize($context, $moduleName, $actionName, $viewName);
  }
  return true;
  }
}