首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Zend Framework 1 常見問題解決方案:MVC 結構、數據庫配置、路由、異常處理、模板輸出

     編輯:PHP 相關知識

背景說明

本文針對 Zend Framework 1 (ZF1) 經典版本(約 2010-2015 年主流)。ZF1 已於 2016 年停止更新,現代專案請使用 Laminas (ZF3 繼承者) 或 Symfony/Laravel。本文作為維護老專案的參考資料保留。

標準 MVC 控制器結構

<?php
class IndexController extends Zend_Controller_Action
{
    public function init()
    {
        // 獲取 View 實例(註冊表模式)
        $this->registry = Zend_Registry::getInstance();
        $this->view     = $this->registry['view'];
        $this->view->baseUrl = $this->_request->getBaseUrl();
    }

    public function indexAction()
    {
        $this->view->word = "I love spurs";
        echo $this->view->render('index.html'); // 渲染模板
    }

    public function addAction()
    {
        if ($this->_request->isPost()) {
            // 處理表單提交
        } else {
            // 顯示添加頁面
            echo $this->view->render('add.html');
        }
    }
}

模板變量傳遞

// 控制器
$this->view->word = "ggg";
$this->view->users = $userModel->fetchAll()->toArray();

// 模板 index.html
<h1><?php echo $this->escape($this->word); ?></h1>
<ul>
<?php foreach ($this->users as $user): ?>
    <li><?php echo $this->escape($user['name']); ?></li>
<?php endforeach; ?>
</ul>

數據庫配置與連接

application/config.ini

[production]
db.adapter  = PDO_MYSQL
db.host     = localhost
db.username = root
db.password = secret
db.dbname   = myapp
db.charset  = utf8

[development : production]
db.dbname = myapp_dev

[testing : production]
db.dbname = myapp_test

Bootstrap 初始化

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initDb()
    {
        $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
        Zend_Registry::set('config', $config);
        
        $db = Zend_Db::factory($config->db->adapter, $config->db->toArray());
        $db->getConnection()->exec("SET NAMES UTF8");
        
        Zend_Db_Table::setDefaultAdapter($db);
        Zend_Registry::set('db', $db);
        return $db;
    }
    
    protected function _initView()
    {
        $view = new Zend_View();
        $view->setEncoding('UTF-8');
        $view->addHelperPath(APPLICATION_PATH . '/views/helpers');
        Zend_Registry::set('view', $view);
        return $view;
    }
}

Model 類定義

class Message extends Zend_Db_Table_Abstract
{
    protected $_name    = 'message';
    protected $_primary = 'id';
    
    // 關聯查詢示例
    public function fetchWithUser()
    {
        $select = $this->select()
            ->setIntegrityCheck(false)
            ->from(['m' => $this->_name])
            ->joinLeft(['u' => 'user'], 'm.user_id = u.id', ['username']);
        return $this->fetchAll($select);
    }
}

路由與 URL 生成

// 單一入口:index.php
// 訪問 /index/add → IndexController::addAction()

// URL 生成(視圖中)
<a href="<?php echo $this->url(['controller' => 'index', 'action' => 'add']); ?>">添加</a>

// 獲取參數
$id = $this->_request->getParam('id');        // 通用
$id = $this->_request->getPost('id');         // 僅 POST
$id = $this->_request->getQuery('id');        // 僅 GET

常見異常與解決方案

1. Invalid controller specified (index.php)

原因:URL 重寫規則將 `index.php` 當作控制器名

解決:Bootstrap 中設置

$front = Zend_Controller_Front::getInstance();
$front->setParam('useDefaultControllerAlways', true);
// 或確保 .htaccess 正確重寫

2. 模板變量輸出亂碼

解決:`$view->setEncoding('UTF-8');` + 數據庫 `SET NAMES UTF8` + 文件保存 UTF-8 無 BOM

3. 數據庫連接失敗

檢查 `pdo_mysql` 擴展、宿主機防火牆、MySQL `bind-address`、用戶權限 `GRANT ... ON db.* TO 'user'@'%'`

CRUD 完整示例

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $msg = new Message();
        $this->view->messages = $msg->fetchAll()->toArray();
    }

    public function editAction()
    {
        $msg = new Message();
        $id  = (int)$this->_request->getParam('id');
        
        if ($this->_request->isPost()) {
            $data = [
                'title'   => $this->_request->getPost('title'),
                'content' => $this->_request->getPost('content'),
            ];
            $msg->update($data, "id = $id");
            $this->_redirect('/index');
        } else {
            $this->view->message = $msg->find($id)->current()->toArray();
        }
    }

    public function deleteAction()
    {
        $id = (int)$this->_request->getParam('id');
        if ($id > 0) {
            $msg = new Message();
            $msg->delete("id = $id");
        }
        $this->_redirect('/index');
    }
}

遷移建議:ZF1 → Laminas / 現代框架

  1. 運行時升級:PHP 5.6 → 8.1+,ZF1 部分組件不兼容
  2. 組件替換:`Zend_Db` → `Laminas\Db` / `Doctrine ORM`,`Zend_View` → `Twig` / `Laminas\View`
  3. 路由重寫:ZF1 路由 → `FastRoute` / `Laminas\Router`
  4. 漸進式重構:Strangler Fig 模式,新功能用現代框架,舊功能逐步遷移
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved