Zend Framework 1.x 以 Zend_Controller_Front (前端控制器)、Zend_View (視圖)、Zend_Db_Table (模型) 為核心。本文提煉最關鍵的入門知識點,作為快速上手與面試複習速查表。
Zend_Controller_Front::getInstance() 取得實例,不可 new。$front->setControllerDirectory('./application/controllers') 或陣列指定模組。$front->dispatch() 接管請求,路由 → 分派 → 行動。$front->setParam('noViewRenderer', true) // 關閉 ViewRenderer (用自定義 View)
$front->setParam('noErrorHandler', true) // 關閉預設 ErrorController
$front->setBaseUrl('/subdir') // 子目錄部署
$front->throwExceptions(true) // 開發環境拋出異常
$front->registerPlugin(new My_Plugin()) 掛載 routeStartup、dispatchLoopStartup 等鉤子。Zend_Controller_Action,方法命名 {ActionName}Action (如 indexAction)。init():構造後、分派前執行,適合初始化 View、ACL、認證。preDispatch() / postDispatch():每個 Action 前/後執行。$this->_request (getParam(), getPost(), isPost())。$this->_response (setBody(), setHeader())。$this->_redirect('/url')、$this->_forward('action', 'controller', 'module')。$this->_helper->viewRenderer、flashMessenger、layout、json。$view = new Zend_View(); $view->setScriptPath('./application/views/scripts')。Zend_Registry::set('view', $view),Controller 取用 Zend_Registry::get('view')。$view->var = 'value' 或 $view->assign(['a'=>1, 'b'=>2])。echo $view->render('index/index.phtml')。$this->escape(), $this->url(), $this->baseUrl(), $this->headTitle(), $this->headLink()。$front->setParam('noViewRenderer', true) 後需手動渲染。$view = new Zend_View_Smarty(); 並設定 template_dir、compile_dir。Zend_Db_Table_Abstract,指定 $_name (表名)、$_primary (主鍵)。Zend_Db_Table::setDefaultAdapter($db) (Bootstrap 設定)。insert(), update($data, $where), delete($where), find($id), fetchRow($select), fetchAll($select)。find() 回傳 Rowset,->current() 取 Row;Row 支援 save(), delete(), toArray()。Zend_Db_Select 鏈式查詢:$table->select()->where()->order()->limitPage()。/:module/:controller/:action/*。/user/edit/id/123 → module=default, controller=user, action=edit, params=[id=123]。$router->addRoute('name', new Zend_Controller_Router_Route(...))。$this->view->url(['action'=>'edit', 'id'=>123])。application/
configs/ # application.ini
controllers/ # IndexController.php, ErrorController.php
models/ # Message.php, User.php
views/
scripts/ # index/index.phtml, error/error.phtml
helpers/ # 視圖助手
filters/ # 視圖過濾器
layouts/ # layout.phtml (Zend_Layout)
library/
Zend/ # 框架核心
public/
index.php # 入口
.htaccess # rewrite
css/, js/, img/
| 錯誤 | 原因 | 解決 |
|---|---|---|
| Invalid controller specified | 控制器類名/檔案名不符 (須 PascalCase + Controller.php) | 檢查類名 IndexController、檔案 IndexController.php |
| View script not found | 腳本路徑錯誤 | 確認 setScriptPath、模組結構 views/scripts/controller/action.phtml |
| No adapter found | Zend_Db_Table 未設定預設適配器 | Bootstrap 中 Zend_Db_Table::setDefaultAdapter($db) |
| Plugin not found | 自動載入失敗 | 確認 library 在 include_path、類名符合 PSR-0/命名規則 |
掌握 **Front Controller 单例分派、Action Controller 生命週期、View 變量賦值與渲染、Zend_Db_Table 表模型 CRUD、路由 URL 對應、目錄結構規範** 六大塊,即可在 ZF1 專案中游刃有餘。理解這些核心機制,遷移至 Laminas (ZF3)、Symfony、Laravel 時,前端控制器→Kernel、Action→Controller、View→Twig/Blade、Table→Entity/Repository,概念完全映射,唯語法與組件化程度不同。