Zend_View 是 Zend Framework MVC 架構中的視圖層核心組件,負責將資料呈現給使用者。其實作主要透過 Zend/View.php 以及 Zend/View/ 目錄下的大量輔助類別與介面組成。以下列出核心檔案結構:
Zend/View.php Zend/View/Abstract.php Zend/View/Exception.php Zend/View/Interface.php Zend/View/Stream.php Zend/View/Helper/ (超過 50 個內建 Helper,如 Form、Navigation、Pagination、Placeholder 等)
這些類別共同構成了功能強大的視圖渲染引擎,支援腳本路徑堆疊、Helper 擴充、過濾器鏈等進階特性。
在 Zend_Controller_Action 中,視圖物件的初始化與渲染流程如下:
views/scripts/、views/helpers/、views/filters/。controller/action.phtml 腳本並渲染,支援指定 action、命名區段、省略控制器前綴。原始碼關鍵邏輯:
public function initView() {
if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) {
return $this->view;
}
// ... 建立 Zend_View,設定 basePath 為模組目錄下的 views
$this->view = new Zend_View(array('basePath' => $baseDir));
return $this->view;
}
Zend_View 繼承自 Zend_View_Abstract,建構子會根據 short_open_tag 設定決定是否註冊 zend.view stream wrapper,以模擬短標籤行為。核心方法 _run() 負責在隔離作用域中 include 視圖腳本。
class Zend_View extends Zend_View_Abstract {
private $_useViewStream = false;
private $_useStreamWrapper = false;
public function __construct($config = array()) {
$this->_useViewStream = (bool) ini_get('short_open_tag') ? false : true;
if ($this->_useViewStream && !in_array('zend.view', stream_get_wrappers())) {
require_once 'Zend/View/Stream.php';
stream_wrapper_register('zend.view', 'Zend_View_Stream');
}
// ...
parent::__construct($config);
}
protected function _run() {
if ($this->_useViewStream && $this->useStreamWrapper()) {
include 'zend.view://' . func_get_arg(0);
} else {
include func_get_arg(0);
}
}
}
addScriptPath($path) / setScriptPath($path):新增/重設腳本搜尋路徑(LIFO 堆疊)。addBasePath($path, $prefix) / setBasePath($path, $prefix):一次設定 scripts、helpers、filters 三種路徑。// Controller 中
$this->view->assign('roles', $roles);
$this->view->assign('num', $num);
// 或直接屬性指派
$this->view->roles = $roles;
$this->view->a = $a;
<?php foreach ($this->data as $item): ?>
<tr><td class="datagrid-cell"><?php echo $this->escape($item->item1); ?></td></tr>
<?php endforeach; ?>
<?php echo $this->baseUrl(); ?>
<?php echo $this->url(array('action' => 'list')); ?>
<?php echo $this->paginationControl($paginator, 'Sliding', 'pagination.phtml'); ?>
<?php echo $this->partial('partial.phtml', array('data' => $data)); ?>
protected function _initViewHelper() {
$boot = $this->bootstrap('View');
$view = $boot->getResource('View');
$view->setHelperPath('Sql/View/Helper', 'Sql_View_Helper');
}
Zend_View 提供了完整的視圖渲染解決方案,支援多路徑堆疊、豐富的 Helper 生態、與 Controller 的無縫整合。掌握其核心類別結構、初始化流程、常用 API 以及視圖腳本撰寫慣例,能有效提升 Zend Framework 專案的開發效率與維護性。