Home Backend Development PHP Tutorial PHP implements guestbook function based on object-oriented

PHP implements guestbook function based on object-oriented

Apr 08, 2018 pm 04:16 PM
php accomplish

这篇文章主要介绍了PHP基于面向对象实现留言本功能,结合了实例,现在分享给大家,需要的朋友可以参考下

本文实例讲述了PHP基于面向对象实现的留言本功能。分享给大家供大家参考,具体如下:

要设计一留言本,一切都将以留言本为核心,抓到什么是什么,按流程走下来,即按用户填写信息->留言->展示的流程进行。

现在用面向对象的思维思考这个问题,在面向对象的世界,会想尽办法把肉眼能看见的以及看不见的,但是实际存在的物或者流程抽象出来。既然是留言本,那么就存在留言内容这个实体,这个留言实体(domain)应该包括留言者姓名、E-mail、留言内容等要素,如下面代码所示


//留言实体类
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;
    }
  }
}
Copy after login


上面的类就是所说的domain,是一个真实存在的、经过抽象的实体模型。然后需要一个留言本模型,这个留言本模型包括留言本的基本属性和基本操作,代码如下所示


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." said: ".self::safe($data)->content.PHP_EOL;
    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 $props)
    {
      $ivar = $props->getName();
      $messagebox->$ivar = trim($props->getValue($data));
    }
    return $messagebox;
  }
  public function delete()
  {
    file_put_contents($this->bookPath,"it's empty now");
  }
}
Copy after login


实际留言的过程可能会更复杂,可能还包括一系列准备操作以及log处理,所以应定义一个类负责数据的逻辑处理,代码如下所示


class leaveModel
{
  public function write(gbookModel $gb, $data)
  {
    $book = $gb->getBookPath();
    $gb->write($data);
    //记录日志
  }
}
Copy after login


最后,通过一个控制器,负责对各种操作的封装,这个控制器是直接面向用户的,所以包括留言本查看、删除、留言等功能。可以形象理解为这个控制器就是留言本所提供的直接面向使用者的功能,封装了操作细节,只需要调用控制器的相应方法即可,代码如下所示


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);
  }
}
Copy after login


测试代码如下所示


$message = new message;
$message->name = 'chenqionghe';
$message->email = 'cqh@cqh.net';
$message->content = 'chenqionghe is a handson boy.';
$gb = new authorControl();//新建一个留言相关的控制器
$pen = new leaveModel();//拿出笔
$book = new gbookModel();//翻出笔记本
$book->setBookPath("E:\\chenqionghe.txt");
$gb->message($pen,$book,$message);
echo $gb->view($book);
//$gb->delete($book);
Copy after login


这样看起来是不是比面向对象过程要复杂多了?确实是复杂了,代码量增多了,也难理解 。似乎体现不出优点来。但是你思考过以下问题吗?

1.如果让很多人来负责完善这个留言本,一部分实体关系的建立,一部人负责数据操作层的代码,这样是不是更容易分工了呢?

2.如果我要把这个留言本进一步开发,实现记录在数据库中,或者添加分页功能,又该如何呢?

要实现上面的第二问题提出的功能,只需在gookModel类中添加分页方法,代码如下所示


public function readByPage()
{
    $handle = file($this->bookPath);
    $count = count($handle);
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    if($page<1 || $page>$count)
      $page = 1;
    $pnum = 9;
    $begin = ($page-1) * $pnum;
    $end = ($begin+$pnum) > $count ? $count :$begin + $pnum;
    for($i=$begin; $i<$end; $i++)
    {
      echo &#39;<strong>&#39;,$i+1,&#39;</strong>&#39;,$handle[$i],&#39;<br />&#39;;
    }
    for($i=1;$i<ceil($count/$pnum);$i++)
    {
      echo &#39;<a href="?page=&#39;.$i.&#39;" rel="external nofollow" rel="external nofollow" >&#39;.$i.&#39;</a>&#39;;
    }
}
Copy after login


然后到前端控制器里添加对应的action,代码如下所示


public function viewByPage(gbookModel $g)
{
    return $g->readByPage();
}
Copy after login


运行结果如下

只需要这么简单的两步,就可以实现所需要的分页功能,而且已有的方法都不用修改,只需要在相关类中新增方法即可。当然,这个分页在实际点击时是有问题的,因为没有把Action分开,而是通通放在一个页面里。对照着上面的思路,还可以把留言本扩展为MySQL数据库的。

这个程序只体现了非常简单的设计模式,这个程序还有许多要改进的地方,每个程序员心中都有一个自己的OO。项目越大越能体现模块划分、面向对象的好处。

下面是完整的代码


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 readByPage()
  {
    $handle = file($this->bookPath);
    $count = count($handle);
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    if($page<1 || $page>$count)
      $page = 1;
    $pnum = 9;
    $begin = ($page-1) * $pnum;
    $end = ($begin+$pnum) > $count ? $count :$begin + $pnum;
    for($i=$begin; $i<$end; $i++)
    {
      echo '',$i+1,'',$handle[$i],'
'; } for($i=1;$i'.$i.''; } } //写入留言 public function write($data) { $this->data = self::safe($data)->name."&".self::safe($data)->email." said: ".self::safe($data)->content.PHP_EOL; 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 $props) { $ivar = $props->getName(); $messagebox->$ivar = trim($props->getValue($data)); } return $messagebox; } public function delete() { file_put_contents($this->bookPath,"it's empty now"); } } class leaveModel { public function write(gbookModel $gb, $data) { $book = $gb->getBookPath(); $gb->write($data); //记录日志 } } 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 viewByPage(gbookModel $g) { return $g->readByPage(); } public function delete(gbookModel $g) { $g->delete(); echo self::view($g); } } $message = new message; $message->name = 'chenqionghe'; $message->email = 'cqh@cqh.net'; $message->content = 'chenqionghe is a handson boy.'; $gb = new authorControl();//新建一个留言相关的控制器 $pen = new leaveModel();//拿出笔 $book = new gbookModel();//翻出笔记本 $book->setBookPath("E:\\chenqionghe.txt"); $gb->message($pen,$book,$message); //echo $gb->view($book); echo $gb->viewByPage($book); //$gb->delete($book);
Copy after login




相关推荐:

PHP实现的获取文件mimes类型工具类示例_php技巧

php实现留言板功能(会话控制)

The above is the detailed content of PHP implements guestbook function based on object-oriented. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles