6.2. 设计一个类
持之以恒,方得始终!
创建一个 Page 类,其功能是快速的创建一个新的 html 页面。
class Page {
protected $content = "";
protected $title = "demo page";
protected $keywords = "demo page very nice.";
protected $buttons = [
"home" => "home.php",
"contact" => "contact.php",
"services" => "service.php",
"site map" => "map.php",
];
public function __set($name, $value) {
$this->$name = $value;
}
public function display() {
echo "<html><head>";
$this->displayTitle();
$this->displayKeywords();
$this->displayStyles();
echo "</head><body>";
$this->displayHeader();
$this->displayMenu($this->buttons);
echo $this->content;
$this->displayFooter();
echo "</body></html>";
}
public function displayTitle() {
echo "<title>" . $this->title . "</title>";
}
public function displayKeywords() {
echo "<meta name ='keywords' content='" . $this->keywords . "' />";
}
public function displayStyles() {
echo "<style>";
echo "h1{color:white;font-size:24px;text-align:center;}";
echo "</style>";
}
public function displayHeader() {
echo "<table>...</table>";
}
public function displayMenu() {
echo "...";
}
// 按钮的url是否指向当前页
public function isUrlCurrentPage($url) {
if (strpos($_SERVER['PHP_SELF'], $url) == false) {
return false;
} else {
return true;
}
}
public function displayButton($width, $name, $url, $active = true) {
if ($active) {
echo "...";
} else {
echo "xxx";
}
}
public function displayFooter() {
echo "...";
}
}
使用它创建一个首页
require("page.php");
$homepage = new Page();
$homepage->content = "<p>this is home page</p>"; // 会调用 __set()
$homepage->display();
我们可以看到,用这种方式,创建一个新页面只需要写少量代码。
当然了,这种方式,所有页面都必须相似。
如果有页面不一样,我们可以创建一个类去继承它,然后重写不一样的部分。
require("./page.php");
class ServicePage extends Page {
private $row2buttons = [
'eng' => 'eng.php',
'std' => 'std.php',
'buzz' => 'buzz.php',
'mission' => 'mission.php'
];
public function display() {
echo "<html><head>";
$this->displayTitle();
$this->displayKeywords();
$this->displayStyles();
echo "</head><body>";
$this->displayHeader();
$this->displayMenu($this->buttons);
$this->displayMenu($this->row2buttons);
echo $this->content;
$this->displayFooter();
echo "</body></html>";
}
}
$services = new ServicesPage();
$services->content = "<p>this is new services page</p>";
$services->display();
我们可以看到,创建一个不同的页面,也只需要简单修改一下即可。
但其实,实际项目中,一般不会这么用,因为会降低性能。
因为前端自己也可以实现组件式构建html页面。
如有任何侵权行为,请通知我删除,谢谢大家!
个人邮箱:865460609@qq.com