LoginSignup
6

More than 5 years have passed since last update.

FuelphpのviewファイルをPC/モバイルによって振り分ける。

Posted at

FuelphpのCoreクラスのViewを拡張する。

肝となるのが、set_filenameメソッドでこれに設定された値に応じてviewファイルを決定する。

では早速拡張

ファイルの配置は以下のとおり
fuel
└app
│ └classes
│   └core ← フォルダ作成
│    └view.php
├views
│ ├common
│ ├mobile
│ └pc
└bootstarp.php

実装

view.php
class View extends \Fuel\Core\View {
    public function set_filename($file) {
    // $fileがcommonから始まるならば、commonフォルダからファイルを取得
    if(strpos($file, "common/") === 0) {

    } else {
      // エージェントがスマホだった場合 
            if ( Agent::is_smartphone() ) {
                $file = 'mobile/' . $file;
      // エージェントが上記以外だった場合
      // とりあえずPCとして扱う 
            } else {
                $file = 'pc/' . $file;          
        }
    }

        return parent::set_filename($file); 
    }           
}

ちなみに上記ファイルでAgent::is_smartphoneを用いているが、実装は以下のリンクより。
http://btt.hatenablog.com/entry/2012/07/04/001254

Viewを拡張したので、bootstrap.phpで設定を行います。

bootstrap.php
// Autoloderに先ほどのViewを設定
Autoloader::add_classes(array(
    'View' => APPPATH.'classes/core/view.php',
));

使用方法

test.php
<?php

class Controller_Test extends Controller {
    public function action_index() {
        // PCからのアクセスなら、「views/pc/test/index.php」
        // モバイルからのアクセスなら、「views/mobile/test/index.php」
        return Response::forge(View::forge('test/index'));
    }

    public function action_common() {
        // PCとモバイルで共通のファイルはこちら
        // 先頭にcommonをつけてアクセス
        return Response::forge(View::forge('common/test/index'));
    }

}

これで快適に振り分けが可能になります。
タブレットからの振り分けを行いたい場合はViewで分岐をしたらOKです。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6