2009年8月2日 星期日

php下的MVC [Zend Framework] 教學

http://phorum.study-area.org/index.php/topic,50393.0/wap2.html

uberr:
Zend Framework是php裡頭其中一種Framework.在台灣跟香港都比較難找到關於Zend Framework的文章.反而CakePHP的文章就很多.所以今天我想分享一下我的心得.我現在的Project都是用Zend Framework來完成.Zend Framework提供大量的module給你使用.它還提供連接Google,Yahoo,Flickr,Amazon..etc Web Services的module.

Zend_Auth // login module
Zend_Db // database module
Zend_Gdata // Google Application module

如果想要了解多些關於MVC,自己到google找吧.

M = Model // 設定連接資料庫的資料[當使用Zend_Db_Table才會用上]
V = View // 顯示的頁面
C = Controller // 控制器,就是你的php程式碼

運作過程:
鍵入網址->Controller->執行Action->回傳給View(顯示頁面)

運作原理:
example: http://www.example.com/auth/login
http://www.example.com // 網址
auth // Controller [控制器]
login // Controller裡面的Action [動作]

程式碼:

class AuthController extends Zend_Controller_Action
{
public function loginAction()
{
// check username and password
}
}

如果你沒有加入任何param係網址裡頭,預設是使用IndexController和Index Action

Zend Framework架構:
application/
controllers/
IndexController.php // 所有Controller一定要大寫開頭
models/
views/
scripts/
index/
index.phtml // 記得是phtml,不是html
htdocs/
scripts/
images/
styles/
library/
.htaccess
index.php

安裝Zend Framework:
1.下載 Zend Framework,PHP5,MYSQL
http://framework.zend.com/releases/ZendFramework-1.0.3/ZendFramework-1.0.3.tar.gz
2.建立Zend Framework架構
3.解壓到Zend架構下的library目錄下,tar -zxf ZendFramework-1.0.3.tar.gz -C /var/www/html/[Zend 目錄]/library/
4.create .htaccess,寫入到 .htaccess
RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php
5.修改httpd.conf,把AllowOverride改成All

現在我們要建立index.php,IndexController.php,index.phtml.index.php 它是用來設定要重導(Route)去邊一個Controller,include module.是一個很重要的file.

廢話少說,來點實作吧~!

index.php
程式碼:

setControllerDirectory('./application/controllers'); // 設定Controller目錄的路徑
$frontController->dispatch();


IndexController.php
程式碼:

view->message = "Zend Framework tutorial"; // 回傳 message
}

public function helloAction()
{
$this->view->message = "Hello World"; // 回傳 message
}
}


index.phtml
程式碼:

message;
?>


http://localhost/index/index
Display Result="Zend Framework tutorial"

hello.phtml
程式碼:

message;
?>


http://localhost/index/hello
Display Result="Hello World"

Demo:
http://wingning.no-ip.org/studyarea/helloworld/
http://wingning.no-ip.org/studyarea/helloworld/index/hello

下載:http://wingning.no-ip.org/studyarea/download/helloworld.tar.gz

這個二個Application是我使用Zend Framework+Dojo開發的.如果大家對Zend Framework和Dojo有興趣,我可以把我其它的心得分享出來.

http://wingning.no-ip.org/lab/invoice
username: admin
password: 123456

http://wingning.no-ip.org/lab/competition

沒有留言:

張貼留言

推到 Twitter!
推到 Plurk!
推到 Facebook!