zend framework的MVC模块很不错,但在此不对MVC作深入的介绍,此文章假使你对 zf 的 MVC 有一定的理解。zend_view 实现了 MVC 中的 view 部分,一般使用 zend_view 都是在控制器中实例化一个 zend_view 对象,然后向 zend_view 对象赋值,然后调用 render 方法来程现一个模板,例子如下:
class SomeController extends Zend_Controller_Action
{
function someAction()
{
$view = new Zend_View();
$view->a = "Hay";
$view->b = "Bee";
$view->c = "Sea";
echo $view->render('some.phtml');
}
}
一般在一个action中,会有相应的模板要程现,zend_controller_action提供了一个更方便的程现模板的方法,看以下例子:
class SomeController extends Zend_Controller_Action
{
function someAction()
{
$this->initView();
$this->view->a = "Hay";
$this->view->b = "Bee";
$this->view->c = "Sea";
echo $this->render();
}
}
以上例子中,先通过 zend_controller_action 中的 initView 方法初始化一个 zend_view 对象,附加到 $this->view 中,然后给 view 赋值,最后调用 zend_controller_action 中的 render 方法程现模板,在 render 方法中并没有指定要程现的模板名,因为这个 render 方法会收集controller的信息来选择要程现的模板。因为调用的是SomeController的someAction,所以 zend_view 会到 application 的目录下找 views/scripts/some/some.phtml ,所以模板放置的位置要符合这个约定才行。一般的 zf 应用的文件结构如下:
application/
controllers/
views/
scripts/
some/ #这个是controller名
some.phtml #这个是以action为文件名,以phtml为后缀的模板文件,zend_view默认.phtml为模板文件类型,可以修改为其它扩展名,如 .tpl。
helpers/
models/
news/
controllers/
views/
scripts/
reader/ #新闻模块的reader控制器(ReaderController)
list.phtml #reader控制器的listAction的模板文件
detail.phtml #reader控制器的detailAction的模板文件
helpers/
models/
docroot/
index.php
images/
styles/
scripts/
library/
zend/
从以上文件结构中,在application目录下的 controllers ,views,models都是放置全局的控制器,模板及模型,news是一个模块(module),每个模块下又有相应的 controllers,views,models目录,放置该模块相应的控制器类,模板及模型类等。以下给出 news 模块的 reader 控制器的实现代码示例,演示在模块中如何调用action相对应的模板:
<?php
class News_ReaderController extends Zend_Controller_Action
{
function init()
{
$this->initView();
}
public function listAction()
{
$this->view->news_records = array('news1','news2','news3');
$this->render(); // 将调用 application/news/views/scripts/reader/list.phtml 模板
}
public function detailAction()
{
$this->view->news_title = 'news title';
$this->view->post_date = date('Y-m-d H:i:s');
$this->view->news_content = 'news content';
$this->render(); // 将调用 application/news/views/scripts/reader/detail.phtml 模板
}
}
?>
看完了以上示例,是否对 zend_controller_action 的 initView() 及 render() 有所了解?