簡介在PHP中採用MVC分離的設計方法

來源:互聯網
上載者:User

為了更好的示範MVC的工作方式,我們使用了一個簡單的新聞文章發布系統作為例子.分為使用MVC和不使用MVC兩種方式.
我們只作一個基本的示範,從資料庫裡讀出一些文章列表,並在頁面上顯示。一般的流程就是,串連資料庫,查詢資料庫,迴圈輸出html結果。下面的代碼就是如此做的。(淡水感覺怪怪的,語言群組織得不好。好在代碼比較容易理解)

PHP代碼
  1. <?php   
  2. mysql_connect(...);   
  3. $result = mysql_query('select * from news order by article_date desc');   
  4. ?>   
  5. <html>   
  6.     <body>   
  7.         <h1>News Articles</h1>         
  8.       <?php while ($row = mysql_fetch_object($result)) { ?>   
  9.                 <h2><?php echo $row->headline ?></h2>              
  10.                 <p>   
  11.                     <?php echo $row->body ?>   
  12.                 </p>   
  13.       <?php } ?>   
  14.     </body>   
  15. </html>  

採用mvc方式.

model:

PHP代碼
  1. <?php      
  2. function get_articles()   
  3. {   
  4.     mysql_connect(...);    
  5.     $result = mysql_query('select * from news order by article_date desc');    
  6.     $articles = array();   
  7.     while ($row = mysql_fetch_objects($result)) {   
  8.         $articles[] = $row;    
  9.     }   
  10. return $articles;   
  11. }   
  12. ?>  

controller:

PHP代碼
  1. <?php   
  2. $articles = get_articles();    
  3. display_template('articles.tpl');   
  4. ?>  

view:

PHP代碼
  1. <html>   
  2. <body>   
  3. <h1>News Articles</h1>   
  4.         <?php foreach ($articles as $row) { ?>   
  5.         <h2><?php echo $row->headline ?></h2>              
  6.             <p>   
  7.                 <?php echo $row->body ?>   
  8.             </p>           
  9.         <?php } ?>     
  10. </body>   
  11. </html>  

譯得不好請多多包涵.原文:http://reinholdweber.com/?p=16

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.