(九)物件導向的設計原則之五

WBOY
發布: 2016-07-30 13:31:44
原創
927 人瀏覽過

一.物件導向的總結:
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教程有興趣的朋友有所幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!