Viewに変数を割り当てる[FuelPHP1.7]

「ビュー(+Template)を使ったhello, world![FuelPHP 1.7]」では、Controller_Templateを継承することでViewを使用しました。 ここではViewへの値の渡し方をみてみます。

以下の例では、Controller_Templateは使用しないでView::forgeを使用してViewを生成しています。

Viewへの値の渡し方

例えば、次のようなViewを作成します。
(例:app/views/website/index.php)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><?php echo $title ?></title>
</head>
<body>
<?php echo $content ?>
</body>
</html>

このViewへ値を渡すには、主に3つの方法があります。

方法1

class Controller_Website extends Controller
{

    function action_index()
    {
        $data = array();

        $data['title']='Sample FuelPHP 1.7';
        $data['content']='hello, world!';

        return View::forge('website/index',$data);
    }
}

方法2

class Controller_Website extends Controller
{

    function action_index()
    {
        $view = View::forge('website/index');

        view->title = 'Sample FuelPHP 1.7';
        view->content = 'hello, world!';

        return $view;
    }
}

方法3

class Controller_Website extends Controller
{

    function action_index()
    {
        $view = View::forge('website/index');

        view->set('tile','Sample FuelPHP 1.7');
        view->set('content','hello, world!');

        return $view;
    }
}

上記以外の方法に「bind」を使う方法がありますが、ドキュメントには 次のような注意書きがあります。

※これらは出力のエンコーディングでクリーニングされないので、安全ではないと見なすべきです。