Viewの使い方[kohana 3.x]

「テンプレート(View)を使ったhello, world![kohana 3.x]」では、Controller_Templateを継承することでViewを使用しました。ここではViewの生成と使い方をみてみます。

Viewの生成

Viewファイルの配置は、applicationディレクトリかmodulesディレクトリの各モジュールディレクトリに Viewディレクトリを作成し、その中に配置します。

application/views
modules/mymodule/views

例えば、applicationディレクトリにviewsディレクトリを作成しtemp.phpを作成します。
(例:public_html/ko3/application/views/temp.php)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<head>
<title>Sample</title>
</head>
<body>
<h1>hello, world!</h1>
</body>
</html>

コントローラーを作成します。(application/classes/controller/hello.php)

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

    public function action_index()
    {
        $this->request->response = View::factory('temp');
    }

}

Viewは、サブディレクトリを作成し分類しておくこともできるようです。例えば、views/pages/about.phpとした場合、 次のように生成します。

public function action_index()
{
    $this->request->response = View::factory('pages/about');
}

Viewの内容を変更する

作成したViewを次のように変更します。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $heading ?></h1>
</body>
</html>

Viewのtitleタグの内容とh1タグの内容を次のように変更しています。

<?php echo $title ?>
<?php echo $heading ?>

この部分をコントローラーで設定し、出力するようにします。

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

    public function action_index()
    {
        $view = View::factory('temp');

        $view->title = 'kohana view sample';
        $view->heading = 'hello, world!';
    }

}

もうひとつの方法として、Viewを生成する時にデータを設定する方法があります。

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

    public function action_index()
    {
        $data['title'] = 'kohana view sample';
        $data['heading'] = 'hello, world!';

        $view = View::factory('temp',$data);
    }

}

bindメソッド

Viewの内容を変更する方法として、bindというメソッドが用意されています。これは参照渡しによる方法です。

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

    public function action_index()
    {
        $view = View::factory('temp')
                  ->bind('heading', $heading)
                  ->bind('title', $title);

        $title = 'kohana view sample';
        $heading = 'hello, world!';

    }

}

setメソッド

Viewには、もうひとつsetメソッドが用意されています。bindメソッドと同じように連想配列に セットされるようですが、動作は違ってきます。

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

    public function action_index()
    {
        $view = View::factory('temp')
                  ->set('heading', 'hello, world!')
                  ->set('title', 'kohana view sample');
    }

}