Zend_Controller Quick Start

剛開始學Zend Framework MVC模式的新手,參考官網的Quick Start以及網路上的相關文章建立MVC模式的架構,為了怕忘記將練習過的寫起來當做筆記。

運作流程

 
http://yourdomain/index/index 為例

1
2
3
4
5
html/index.php (決定哪個控制器)
         ↓
application</code>/IndexController.php (建立控制器並設定動作)
         ↓
views/scripts/index/index.phtml (輸出html頁)

準備

Zend Framework 官網下載Zend Framework

建立目錄結構

參考官方提供
目錄 library/Zend 為在官網下載的library,將它解壓縮後放置這裡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
library/
    Zend/
application/
    controllers/
        IndexController.php
    models/
    views/
        scripts/
            index/
                index.phtml
        helpers/
        filters/
html/
    .htaccess
    index.php

建立htaccess

檔案位置:html/.htaccess

1
2
3
4
5
6
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

建立index.php

檔案位置:html/index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 設定zend library位置
set_include_path('.'.PATH_SEPARATOR.'../library'.PATH_SEPARATOR . get_include_path());
 
// 利用registerAutoload方式載入zf class
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();
 
// 載入 Zend_Controller_Front
Zend_Loader::loadClass('Zend_Controller_Front');
 
// 建立一個前景控制器
$frontController = Zend_Controller_front::getInstance();
 
//設定控制器的目錄位置
$frontController->setControllerDirectory('./application/controllers');
 
//分發所設定控制器
$frontController->dispatch();

建立控制器(controller) & 設定動作(Action)

位置: application/controllers/IndexController.php
注意: 控制器的php檔名字母必須為大寫

1
2
3
4
5
6
class IndexController extends Zend_Controller_Action{
    public function indexAction(){
 
       $this->view->message = "Hello word";
    }
}

建立輸出頁

位置:application/views/scripts/index/index.phtml
注意: index檔案副檔名必須為phtml

1
echo $this->message;

顯示

注意: 第一個index為控制器(controller),第二個index為動作(Action)
http://yourdomain/index
http://yourdomain/index/index

1
Hello word

參考資料

Related Posts with Thumbnails

相關文章