問題描述
我已經閱讀了一段時間關于 MVC 設計的文章,似乎正式視圖調用模型中的對象和方法,構建并輸出視圖.
I've been reading about MVC design for a while now and it seems officially the View calls objects and methods in the Model, builds and outputs a view.
我認為這主要是錯誤的.
I think this is mainly wrong.
控制器應該采取行動并檢索/更新模型內的對象,選擇適當的視圖并將信息傳遞給它,以便它可以顯示.視圖中只應出現粗略和基本的 PHP 變量/簡單的 if 語句.
The Controller should act and retrieve/update objects inside the Model, select an appropriate View and pass the information to it so it may display. Only crude and rudiementary PHP variables/simple if statements should appear inside the View.
如果View從Model中得到了它需要顯示的信息,那么View里面肯定會有很多PHP——完全違背了分離呈現邏輯的點.
If the View gets the information it needs to display from the Model, surely there will be a lot of PHP inside the View -- completely violating the point of seperating presentation logic.
推薦答案
與所有編程一樣,我們需要務實.視圖應該只包含表示邏輯.該邏輯可以非常簡單,也可以非常復雜.只要該邏輯只處理屏幕上顯示的內容、報告上打印的內容等.
As with all things programming we need to be pragmatic. A view should only contain presentation logic. That logic can be very simple or can be quite complex. As long as that logic only handles what is displayed on the screen, printed on the report, etc.
控制器應該采取行動并檢索/更新模型內的對象,選擇適當的視圖并將信息傳遞給它,以便它可以顯示.
The Controller should act and retrieve/update objects inside the Model, select an appropriate View and pass the information to it so it may display.
你傳遞的信息是什么?可能是模型的一個子集.你可以創建一個只包含視圖應該知道的信息的新類,或者只傳遞模型并確保你只訪問適當的數據.無論如何,視圖應該可以自由查詢傳入的模型,以便能夠顯示視圖.
What is this information you are passing? Possibly a subset of a model. You could create a new class containing only the information the view should know about or just pass along the model and make sure you only access appropriate data. Anyway, the view should be free to query this passed in model to be able to display a view.
爭議點在于,從視圖的角度來看,您是否應該能夠繞過控制器直接更新模型.這就是務實的地方.我認為有些情況可以保證直接更新模型.特別是如果您可以使用數據綁定.您可以為模型的屬性分配一個文本框,并讓更新自動發生.如果有很多簡單的屬性設置,這種方式可以在控制器中節省一堆代碼.MVC 不是一套一成不變的規則.它的指導方針是,正確使用可以產生更好的代碼,但如果使用過于嚴格,則會導致痛苦和痛苦.
The point of controversy is if you from the view should be able to update the model directly, bypassing the controller. This is where the pragmatic side comes in. I think there are cases that can warrant updating the model directly. Especially if you can use data bindings. The you can assign a text box to a property of the model and let the update automagically happen. If there are a lot of simple property setting this approach can save a bunch of code in the controller. MVC is not a set of rules set in stone. It's guidelines that when used correctly can produce better code but if used too rigorously can lead to pain and suffering.
務實!
這篇關于MVC:模型視圖控制器——視圖調用模型嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!