概要
- viewの指定があれば通常どおり
- なければ「コントローラ名/アクション名」で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は
- app/modules/モジュール/views
- app/views
の順に検索してくれる。