继承模板控制器–kohana3使用手册
第二步,当用 Kohana 创建一个模板的网站需要继承 Controller_Template 类。虽然这不是必须的,因为你可以直接使用 Controller_Template 。继承控制器是一种很好的做法,那样你能轻松的设置默认值并且基于请求自定义输出。
我们的控制器该如何组织
■ Controller_Template extends Controller
■ Controller_Demo extends Controller_Template
■ Controller_Page extends Controller_Demo
我们自定义的模板控制器叫作 demo.php ,创建在下列目录中
/home/kerkness/kohana/application/classes/controller/demo.php
这是我们定制的模板控制器
< ?php defined('SYSPATH') or die('No direct script access.');
class Controller_Demo extends Controller_Template
{
public $template = 'demo/template';
/**
* before()方法在你的控制器动作执行前被调用
* 在我们的模板控制器中,我们覆盖了这个方法,那么我们就能设置默认值。
* 那么这些变量需要改变的时候我们的控制器也能使用它们
*/
public function before()
{
parent::before();
if ($this->auto_render)
{
// Initialize empty values
$this->template->title = '';
$this->template->content = '';
$this->template->styles = array();
$this->template->scripts = array();
}
}
/**
* after()方法在控制器动作执行后调用
* 在我们的模板控制器中,我们覆写了这个方法,那么我们就能
* 在模板显示之前做最后的一些改变
*/
public function after()
{
if ($this->auto_render)
{
$styles = array(
'media/css/screen.css' => 'screen, projection',
'media/css/print.css' => 'print',
'media/css/style.css' => 'screen',
);
$scripts = array(
'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',
);
$this->template->styles = array_merge( $this->template->styles, $styles );
$this->template->scripts = array_merge( $this->template->scripts, $scripts );
}
parent::after();
}
}
我们的模板控制器执行了两个主要函数:
1. 准备默认值并通过使用 before() 方法在动作执行前配置
2. 通过使用 after() 方法在动作执行后修改并验证数值并在所有响应之前显示
在上面的实例中,before() 方法将我们的控制器中的变量设置为空变量。after()方法增加了我们的网站所有页面都需要的默认 javascript 和 css 文件