LoginSignup
1
1

More than 5 years have passed since last update.

FuelPHP Templateコントローラでviewファイルを自動的に読み込む

Posted at

概要

  1. viewの指定があれば通常どおり
  2. なければ「コントローラ名/アクション名」でviewファイルを検索・生成 (アクションがusers/indexならviewファイルの位置はviews/users/index)

という形にします。

変更前のControllerイメージ

controller/users.php
public function action_create()
{
    ()
    $this->tmplate->content = View::forge('users/create');
}

public function action_register()
{
    ()
    $this->tmplate->content = View::forge('users/create');
}

public function action_index()
{
    ()
    $data = array(
        'users' => Model_User::find('all'),
    );
    $this->tmplate->content = View::forge('users/index', $data);
}

変更後のControllerイメージ

controller/users.php
public function action_create()
{
    ()
}

public function action_register()
{
    ()
    $this->tmplate->content = View::forge('users/create');
}

public function action_index()
{
    ()
    $data = array(
        'users' => Model_User::find('all'),
    );
    $this->set_template_data($data); //追加メソッド
}

ソース

以下を基底クラスにします。モジュール、深い階層対応。
viewにdataを渡すためのset_template_dataというメソッドだけ新設しています。
代わりに$this->template->set_globalを使う手もあります。

class Controller_Base extends Controller_Template
{
    protected $data;

    protected static function get_view_filename()
    {
        $controller_fullname = Request::active()->controller;
        $pattern = array(
            '/^(.*\\\)*Controller_/', //namespace & prefix
            '/_/',                   //separator
        );
        $replace = array(
            '',
            '/'
        );
        $controller = preg_replace($pattern, $replace, $controller_fullname);
        $action     = Request::active()->action;
        return sprintf('%s/%s', $controller, $action);
    }

    public function before()
    {
        parent::before();
        $this->template->title   = '';
        $this->template->content = '';
    }

    public function after($response)
    {
        $res = parent::after($response);
        if (! $res->body()->content) {
            $view = static::get_view_filename();
            $res->body()->content = View::forge($view, $this->data);
        }
        return $res;
    }

    public function set_template_data($data)
    {
        $this->data = $data;
        return $this;
    }
}

ポイント

afterメソッドに到達した時点で
$this->template->contentがnullだとこけるので
あらかじめbeforeで空文字などをセットしておく。
$this->template->content = '';

Requestクラスで取得したコントローラ名にはprefix(Controller_)、
名前空間(モジュール名)が付加されているので全部取り除く。

モジュール内のコントローラでviewを指定した場合Fuelは

  1. app/modules/モジュール/views
  2. app/views

の順に検索してくれる。

1
1
0

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
1
1