本篇文章将探讨網站布局的實作,以前也寫過和視圖層相關的文章==>點選檢視<==
承接上篇文章的思路,本篇文章讨論的重點是“如何将子產品化的塊用xml組織起來?”
下面是我總結的視圖層的設計要點:
-定義網站的公共布局,以供其他布局調用和修改
-網站同一個URL可能會有多種狀态,例如Logged In/Logged Out,不同狀态的布局可以不同;
-網站所有的頁面都是由路由系統組織起來的,是以包含頁面布局的xml檔案也應當采用和路由系統相似的機構,便于和頁面互相對應
在這裡,以句柄(handle)來區分不同的布局。句柄在系統執行時生成,一個頁面可以關聯多個句柄,每個句柄代表一層,這樣就做到了分層。
首先定義公共層<default>,所有的頁面都以它為基礎;
然後定義目前頁面層<module_controller_action>;
如果頁面需要處理不同的狀态,則定義狀态層
最後,在渲染頁面時将所有層的布局相融合,生成最終的布局資料。
有了頁面布局的xml檔案之後,結合View類和template模版,就可以開始渲染頁面了。
假如我要定義一個品字形網頁:
公共布局:
1 2 3 4 5 6 7 8 9 | <default> <block class="Top" name="top" as="public.top" template="top.phtml"> <block class="Top_Log" name="top.log" template="top_log.phtml" /> <block class="Top_Links" name="top.links" template="top_links.phtml" /> </block> <block class="Left" name="left" as="public.left" template="left.phtml"/> <block class="Right" name="right" as="public.right" template="right.phtml"/> <block class="footer" name="footer" as="public.footer" template="footer.phtml"/> </default> |
其中,block表示塊,class表示塊的PHP類,name表示塊的名稱,as表示塊是公共的,可以被其他塊修改,“top.log”和“top.links”是“top”的子塊(child)
首頁布局:
1 2 3 4 5 | <home_index_index> <reference name="public.right"> <block class="Banner" name="banner" template="banner.phtml"/> </reference> </home_index_index> |
其中,reference表示引用公共塊,name表示将要引用的塊的as屬性,
活動頁布局:
1 2 3 | <promotion_index_index> <update>home_index_index </update> </promotion_index_index> |
其中,<update/>表示新增home_index_index句柄,意味着渲染時程式也會讀取<home_index_index/>中的内容。
活動頁2布局:
1 2 3 4 5 6 | <promotion2_index_index> <update>home_index_index </update> <reference name="public.right"> <remove name="banner"/> </reference> </promotion2_index_index> |
其中,<update/>表示新增home_index_index句柄,<remove/>表示去掉“public.right”中的“banner”塊
當被通路的頁面開始渲染時,程式依次讀取各句柄中的資料并按照規則生成布局資料。
Block對象$block如何與Template産生關聯?
介紹block類的3個方法:
public function toHtml(){}
public function getChild($child){}
public function getChildHtml($child){}
上述3個方法是每一個Block類都具有的方法,這3個方法主要用來在template中調用來産生HTML:
$block->toHtml()将會傳回$block的HTML;
//$child是定義在布局xml中的子塊的name屬性
$block->getChild($child)将會傳回一個子Block對象,這個子block對象是在布局xml中定義的;
$block->getChildHtml($child)将會傳回一個子Block對象的HTML,這個子block對象是在布局xml中定義的,相當于$block->getChild($child)->toHtml();
通過周而複始的調用getChildHtml($child),最終就可以獲得整個頁面的HTML。
如果您覺得閱讀本文對您有幫助,歡迎轉載本文,但是轉載文章之後必須在文章頁面明顯位置保留此段聲明,否則保留追究法律責任的權利。
作 者:www.jpdou.top
原文連結:http://www.jpdou.top/website-layout-display/
轉載于:https://www.cnblogs.com/jpdoutop/p/website-layout-display.html