codeigniterで、PC版とスマフォ版のテンプレートを自動で振分ける方法

CodeIgniter PHP user_agent 未分類

small__6757040007

 

スマフォ版とPC版のテンプレートを切り替えるために、毎回コントローラでユーザーエージェントをチェックして振り分け処理が面倒になり

$this->load->view();を指定すると内部で自動にPCフォルダ内のview、スマフォフォルダ内のviewを表示するように対応してみました。

loadクラスを拡張したクラスで振り分け処理を行う

前回、headerfooterをloadで設定する方法で行った延長で、以下のようにMY_Loader クラスを作成します。

class MY_Loader extends CI_Loader {
 
    function __construct(){
        parent::__construct();
    }
    
    // PC版、スマフォ版ともに同じviewを使いたい場合はこの関数を呼び出す
	public function done_common_view () {
		$this->done_common_view = true;
	}
 
 
    public function view($view, $vars = array(), $return = FALSE)
    {
		$ci =& get_instance();

		if($ci->agent->is_mobile()) {
			$this->header_path = APPPATH . "views/sp/header.php";
			$this->footer_path = APPPATH . "views/sp/footer.php";
		}
		else {
			$this->header_path = APPPATH . "views/pc/header.php";
			$this->footer_path = APPPATH . "views/pc/footer.php";
		}
		
        $class = $ci->router->fetch_class(); // Get class
        $action = $ci->router->fetch_method(); // Get action
 
        // 共通headerを読み込まない処理をいれる
        if(strpos($action, 'ajax') !== FALSE  || $class == "static") {
        } else{
            $header =  $this->_ci_load(array('_ci_path' => $this->header_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
        }
 
        // ボディ
		if($this->done_common_view) {
			//共通の場合はviewsフォルダ以下に置く
			$body =  $this->_ci_load(array('_ci_view' => "$view", '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		}
		elseif($ci->agent->is_mobile()) {
			//スマフォ版の場合はviews/sp/フォルダ以下に置く
			$body =  $this->_ci_load(array('_ci_view' => "sp/$view", '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		}
		else {
			//PC版の場合はviews/pc/フォルダ以下に置く
			$body =  $this->_ci_load(array('_ci_view' => "pc/$view", '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
		}
 
        // 共通footerを読み込まない処理をいれる
        if(strpos($action, 'ajax') !== FALSE  || $class == "static") {
        } else{
            $footer =  $this->_ci_load(array('_ci_path' => $this->footer_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
        }
 
        if($return) {
            return $body;
        }
    }
}
?>

使い方は、$this->load->view(“welcome”);と指定するとPC版はapplication/views/pc/welcome.php スマフォ版はapplication/views/sp/welcome.phpのビューを読み込みます。

また、$this->load->done_common_view();をviewを呼び出す手前に呼び出すと、application/views/welcome.phpのビューを読み込みます。

関連記事

コメント

この記事へのコメントはありません。

カテゴリー

お問い合わせはコチラ!