>  기사  >  백엔드 개발  >  (九)面向对象的设计原则之五

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

WBOY
WBOY원래의
2016-07-30 13:31:44929검색

一.面向对象的总结:
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으로 문의하세요.