LoginSignup
0
0

More than 5 years have passed since last update.

FuelPHPのViewにテンプレート機能を追加してみた

Posted at

FuelPHPのよく使う機能をPackageとして切り出してみるその①

パッケージ名

TemplateView (Github)

概要

Presenter/Viewクラスにテンプレート機能を追加するパッケージ

作った動機

FuelPHPのViewを作るときに、HTMLの共通部分はテンプレート化したい。
そんな時のために、FuelPHPには標準でTemplateControllerクラスが用意されている。
しかし、MVCの役割的にControllerにViewの拡張機能が実装されているのってなんか気持ち悪い。
Viewの拡張機能であれば、Viewクラス(ついでにPresenterクラス)に実装したほうがいいのではないかと思いやってみた。

使い方(実装例)

パッケージの読み込み

fuel/app/config/config.php
return array(
    'always_load'  => array(
        'packages'  => array(
            // パッケージをロード
            'templateview',
        ),
    ),
);

Presenter基底クラスを自作のクラスに差し替える

fuel/app/bootstrap.php
\Autoloader::add_classes(array(
    // Add classes you want to override here
    // Example: 'View' => APPPATH.'classes/view.php',
    // Presenter基底クラスを自作のクラスに差し替える
    'Presenter' => APPPATH.'classes/presenter.php',
));

ControllerでPresenterインスタンスを生成する

fuel/app/classes/controller/sample.php
class Controller_Sample extends \Controller
{
    public function action_index()
    {
        // Viewをセット
        $view = \Presenter::forge('sample/index');

        return \Response::forge($view);
    }
}

Presenterの基底クラスで共通部品のViewをセットする

fuel/app/classes/presenter.php
class Presenter extends \Fuel\TemplateView\Presenter
{
    /**
     * Executed before the view method
     */
    public function before()
    {
        // 共通のViewをテンプレートに分割してセット

        // Sets the view's head template filename.
        $this->set_template_head('template/head');

        // Sets the view's header template filename.
        $this->set_template_header('template/header');

        // Sets the view's footer template filename.
        $this->set_template_footer('template/footer');

        // Sets the view's foot template filename.
        $this->set_template_foot('template/foot');
    }
}

Presenterの派生クラスで、各ページ個別の変数をセットする。

fuel/app/classes/presenter/sample/index.php
class Presenter_Sample_Index extends \Presenter
{
    /**
     * The default view method
     * Should set all expected variables upon itself
     */
    public function view()
    {
        // 変数をセットする
        // ※ここでセットした変数は全View内から参照可能
        $this->set('title', 'Page Title');
    }
}

まとめ

PresenterクラスでViewのテンプレート管理ができるようになり、個人的にはすっきりした。
今のところ、4種類のテンプレートファイルを保持できるようにしているが、
そのうち配列で管理して、個数を可変にするかも。

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