PHP 编写大型网站问题集

2019-04-09 21:07:22王旭


 return implode ("", $characters);
}

?>

四、客户端和服务器端代码的分离
  客户端和服务器端代码的在PHP程序中实际上就是HTML代码和PHP语言代码,很多人把HTML和PHP语句混合在一个文件里,使得这文件很大,这种风格对程序的维护和再开发很不利,不适合大型站点的开发。一般有两种方法把HTML和PHP语句分开:
1、编写专用API,例如:

index.php The Client side

<?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>
</table>
</body>
</html>

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",
mysql_errno (), mysql_error ()));

$site_info = mysql_fetch_object ($sth);

function print_header ()
{
 global $site_info;
 print $site_info->header;
}

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 "ttt
 <a href="$links[$i]">$names[$i]</a>
 n<br>n";
}
}
?>

这种方法使得程序看起来比较简洁,而且执行速度也较快。

2、使用模板的方法
这种方法使得程序看起来更简洁,同样实现上面的功能,可用以下代码:

<html>
<head>
<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的页面制作人员也能修改模板文件。这种方法的缺点是执行效率不高,因为要解释模板文件。同时实现起来也比较复杂。
相关文章 大家在看