首页 >后端开发 >php教程 >(九)面向对象的设计原则之五

(九)面向对象的设计原则之五

WBOY
WBOY原创
2016-07-30 13:31:44997浏览

一.面向对象的总结:
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

<?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教程有兴趣的朋友有所帮助。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn