Home >Backend Development >PHP Tutorial >(9) Object-oriented design principle five
one. Object-oriented summary:
1. High abstraction is conducive to high summary.
2. Code is documentation.
Two. Example of a guestbook made with object-oriented thinking:
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);
Copyright statement: This article is an original article by the blogger without the permission of the blogger. No reproduction allowed.
The above has introduced the fifth object-oriented design principle (9), including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.