四、客户端和服务器端代码的分离   PHP程序员站--PHP程序员之家  
     客户端和服务器端代码的在php程序中实际上就是html代码和php语言代码,很多人把html和php语句混合在一个文件里,使得这文件很大,这种风格对程序的维护和再开发很不利,不适合大型站点的开发。一般有两种方法把html和php语句分开:  www phperz com  
  1、编写专用api,例如:        index.php ? the client side   PHP程序员站  
 
 
    
        
            以下为引用的内容:
    <?php include_once ("site.lib"); ?>    <html>    <head>    <title> <?php print_header (); ?> </title>    </head>    <body>    <h1> <?php print_header (); ?> </h1>    <table border="0" cellpadding="0" cellspacing="0">    <tr>    <td width="25%">    <?php print_links (); ?>    </td>    <td>    <?php print_body (); ?>    </td> 
              </tr>  PHP程序员站--PHP程序员之家    </table>    </body>    </html>   www phperz com  
             | 
         
    
 
 PHP程序员站--PHP程序员之家  
   site.lib ? the server side code      
 
    
        
            以下为引用的内容: <?php       $dbh = mysql_connect ("localhost", "sh", "pass")    or die (sprintf ("cannot connect to mysql [%s]: %s",    mysql_errno (), mysql_error ()));    @mysql_select_db ("mainsite")    or die (sprintf ("cannot select database [%s]: %s",    mysql_errno (), mysql_error ()));        $sth = @mysql_query ("select * from site", $dbh)    or die (sprintf ("cannot execute query [%s]: %s",  PHP程序员站     mysql_errno (), mysql_error ()));        $site_info = mysql_fetch_object ($sth);        function print_header ()    {     global $site_info;     print $site_info->header; 字串4    }        function print_body ()    {     global $site_info;     print nl2br ($site_info->body);    }        function print_links ()    {     global $site_info;         $links = explode ("\n", $site_info->links);     $names = explode ("\n", $site_info->link_names);        for ($i = 0; $i < count ($links); $i++)    {     print "\t\t\t     <a href=\"$links[$i]\">$names[$i]</a>     \n<br>\n";    }    }    ?>   | 
         
    
 
 www.phperz.com     PHP程序员站--PHP程序员之家  
   这种方法使得程序看起来比较简洁,而且执行速度也较快。        2、使用模板的方法   www phperz com  
   这种方法使得程序看起来更简洁,同样实现上面的功能,可用以下代码:  PHP程序员站--PHP程序员之家  
 
    
        
            以下为引用的内容:  <html>    <head> 字串8    <title>%%page_title%%</title>    </head>    <body %%body_properties%%>    <h1>%%page_title%%</h1>    <table border="0" cellpadding="0" cellspacing="0">    <tr>    <td width="25%">%%page_links%%</td>    <td>%%page_content%%</td>    </tr>    </table>    </body>    </html>   | 
         
    
 
 PHP程序员站        用占位符代替要动态生成的内容,然后用一解析程序分析该模板文件,把占位符用际的内容替换。种方法使得即使不会使用php的页面制作人员也能修改模板文件。这种方法的缺点是执行效率不高,因为要解释模板文件。同时实现起来也比较复杂。 
  |