引言
本章會針對MVC的 觀念做一個簡短的介紹,因為它被實作在Cake裡。 如果您第一次接觸到MVC(Model View Controller) 這個名詞,無疑的,本章是為您而寫的。 我們會先大概說明一下MVC的觀念,接下來說明CakePHP裡的MVC應用程式,最後用MVC模式舉一些簡單的CakePHP範例。
本章會針對MVC的 觀念做一個簡短的介紹,因為它被實作在Cake裡。 如果您第一次接觸到MVC(Model View Controller) 這個名詞,無疑的,本章是為您而寫的。 我們會先大概說明一下MVC的觀念,接下來說明CakePHP裡的MVC應用程式,最後用MVC模式舉一些簡單的CakePHP範例。
Model-View-Controller是一種軟體設計模式,幫您將程式碼合理的分離,使它更容易被重用與管理,當然看起來也會更好。 Gang of Four小組首先提出Model-View-Controller。Dean Helman寫到(出自Objective Toolkit Pro白皮書):
"The MVC paradigm is a way of breaking an application, or even just a piece of an application's interface, into three parts: the model, the view, and the controller. MVC was originally developed to map the traditional input, processing, output roles into the GUI realm.
Input -> Processing -> Output
Controller -> Model -> View
"The user input, the modeling of the external world, and the visual feedback to the user are separated and handled by model, view port and controller objects. The controller interprets mouse and keyboard inputs from the user and maps these user actions into commands that are sent to the model and/or view port to effect the appropriate change. The model manages one or more data elements, responds to queries about its state, and responds to instructions to change state. The view port manages a rectangular area of the display and is responsible for presenting data to the user through a combination of graphics and text."
在Cake中,Model代表特定的資料表記錄。 Model同時含有資料檢驗的規則,當資料新增或更新時自動套用。 View負責顯示使用者介面,在Cake中以view檔案負責,檔案內含標準的HTML和PHP程式。 Controller則負責處理來自伺服器的request。 它會取得使用者輸入的資料(URL或POST資料),套上企業邏輯,與透過Model自資料庫存取資料,最後使用合適的view將資料輸出。
為了讓您更容易的開發應用程式,Cake不只在管理物件的溝通上應用到此模式,連檔案的存放都以此觀念實作,接下來就要詳細介紹。
Cake檔案封包解開時會看到三個主要的資料匣:
cake資料匣放置Cake的核心函式庫,一般來說,您永遠不需要碰到它。
app資料匣是您放置應用程式的資料匣,所有檔案都放在這裡。 cake資料匣與app資料匣分開,可以讓不同的應用程式共同使用一份Cake函式庫,同時也更容易將Cake升級為新版本: 只需下載最新版的Cake,把Cake資料匣內的核心函式庫換掉即可,完全不需要重寫應用程式。
vendors資料匣是放置第三方函式庫的地方。手冊後面會教到更多關於 vendors的知識,基本觀念就是透過Cake的vender()函式,取用放在 vendors資料匣的類別。
讓我們看看整個檔案目錄結構: