一.面向对象的总结:
1.高度抽象有利于高度总结。
2.代码即文档。
二.以面向对象思想做的留言本实例:
message.php
<?php
/*
* 留言实体类
*/
class message{
public $name;
public $email;
public $content;
public function __set($name,$value){
$this->$name = $value;
}
public function __get($name){
if (!isset($this->$name)){
$this->$name = null;
}
}
}gbookModel.php
<?php
/*
* 留言本模型
*/
class gbookModel{
private $bookPath;
private $data;
public function setBookPath($bookPath){
$this->bookPath = $bookPath;
}
public function getBookPath(){
return $this->bookPath;
}
public function open(){
}
public function close(){
}
public function read(){
return file_get_contents($this->bookPath);
}
//写入留言
public function write($data){
$this->data= self::safe($data)->name."&".self::safe($data)->email."\r\nsaild:\r\n".self::safe($data)->content;
return file_put_contents($this->bookPath,$this->data,FILE_APPEND);
}
public static function safe($data){
$reflect = new ReflectionObject($data);
$props = $reflect->getProperties();
$messagebox = new stdClass();
foreach($props as $prop){
$ivar = $prop -> getName();
$messagebox ->$ivar= trim($prop->getValue($data));
}
return $messagebox;
}
public function delete(){
file_put_contents($this->bookPath,'it\'s empty now');
}
}leaveModel.php
<?php
//业务逻辑
class leaveModel{
public function write(gbookModel $gb,$data){
$book = $gb->getBookPath();
$gb->write($data);
}
}view.php
ThinkPHP是一个快速、简单的基于MVC和面向对象的轻量级PHP开发框架,遵循Apache2开源协议发布,从诞生以来一直秉承简洁实用的设计原则,在保持出色的性能和至简的代码的同时,尤其注重开发体验和易用性,并且拥有众多的原创功能和特性,为WEB应用开发提供了强有力的支持。 3.2版本则在原来的基础上进行一些架构的调整,引入了命名空间支持和模块化的完善,为大型应用和模块化开发提供了更多的便利。
<?php
include "gbookModel.php";
include "leaveModel.php";
include "message.php";
class authorControl{
public function message(leaveModel $l,gbookModel $g,message $data){
$l->write($g,$data);
}
public function view(gbookModel $g){
return $g->read();
}
public function delete(gbookModel $g){
$g->delete();
echo self::view($g);
}
}
//以下是测试
$message = new message();
$message->name = 'phper';
$message->email = 'test@test.com';
$message->content = 'love php';
$gb = new authorControl();
$pen = new leaveModel();
$book = new gbookModel();
$book->setBookPath('test.txt');
$gb->message($pen,$book,$message);
echo $gb->view($book);
$gb->delete($book);版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了(九)面向对象的设计原则之五,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。









