システム作っていると、メニューとかタイトルとか共通部分が出てくる。
イチイチactionで同じ処理をつけるのは、面倒くさいし、書き換えるとき不便だし、同じこと書くのってどうなの?感。
同じデザインならば、処理部分だけ作って、他は共通処理にしちゃおう!
とする場合の話。
最初『ざっくりFuelPHPの使い方 - Qiita』を参照にテンプレートの分割していた。
一方『views/template.php』がある場合において『php oil』で作成されるものはController_Template継承したものになる。
だが、基本的に『Controller_Base』を使うように作成するわけだから、当然『views/template.php』を書き換えているので、Baseで設定した項目においては当然エラーがボロボロ出る。
Controller_TemplateをController_Baseに書き換えるだけだが、複数あるともう面倒~。
時間が経過とともに、継承先を変えていたことをスッカリ忘れていたりしたらば、もう調べだして無駄な時間を浪費して、泣ける通り越して最早ウケる。(実体験)
なので、それはそれで使えるようにする。
つまり『$title』『$content』を呼ぶだけの『views/template.php』を作る。
それとは別に新しく『views/template/template.php』を作る。
そしてController_Baseに上記のテンプレートの指定($template='template/template';)を追加。
と『Controller_Base』を前提としてきたけど
oil g admin 【対象】
で『controller/base.php』が作られる。
なので『Controller_Base』ではなく『Controller_Mytemplate』とする。
各々考えたらいいです。
※上記ディレクトリ名とファイル名は仮なので、自分の環境にあわせて変更。
上記までを前提として、用意するファイルの基本として下記にまとめておく
fuel\app\classes\controller\mytemplate.php
class Controller_Mytemplate extends Controller_Template
{
public $template = 'template/template';
public function before()
{
parent::before();
$this->template->title = 'タイトル共通';
// $this->templateにセットしているので$this->template->menuにセットしている訳ではないから、テンプレート毎にセットが必要
$arr_menu['title'] = $this->template->title;
$this->template->menu = View::forge('template/menu',$arr_menu);
// 複数のテンプレートに一括で設定したいならglobalでセット出来る
$this->template->set_global($arr_menu);
}
public function after($response)
{
// 自身のレスポンスオブジェクトを作成する場合は必要ない。
$response = parent::after($response);
// after() は確実に Response オブジェクトを返すように
return $response;
}
}
使うController
こんな感じで使う
class Controller_Test extends Controller_Mytemplate
{
public function action_index()
{
$data['test'] = '100点';
//template.phpのcontentとアクション毎のviewをbindさせる
$this->template->content = View::forge('numbers3/index');
$this->template->content->set($data); // 別にセットも出来る
//default設定を変えず、template.phpのファイル名を変更しない場合はtemplateのviewオブジェクトを返す
// return Response::forge(View::forge('test/index',$data));
}
}
fuel\app\views\template.php
各々の状況にあわせて変わるけど、基本的にこんな感じ。
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<header><title><?php echo $title; ?></title></header>
<div class="container-fluid">
<div class="row">
<div class="container"><?php echo $content; ?></div>
</div>
</div>
<footer class="footer">© Copyright <?php echo date('Y');?> <?php echo $title; ?></footer>
</body>
</html>
fuel\app\views\template\template.php
各々の状況にあわせて変わるけど、基本的にこんな感じ。
<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<header><title><?php echo $title; ?></title></header>
<div class="container-fluid">
<div class="row">
<div class="container col-sm-8"><?php echo $content; ?></div>
<div class="col-sm-4 menu"><?php echo $menu; ?></div>
</div>
</div>
<footer class="footer">© Copyright <?php echo date('Y');?> <?php echo $title; ?></footer>
</body>
</html>

コメント