php - OOP 设计问题 - 避免在类似的类中重复代码?

标签 php oop design-patterns

我正在用 PHP 为我们正在开发的网站的服务器端部分编写一堆类。这些类看起来像这样:

class SomeEntity {
    // These fields are often different in different classes
    private $field1 = 0, $field2 = 0, ... ;

    // All of the classes have one of these
    static function create($field1, $field2) {
        // Do database stuff in here...
    }

    // All of the classes have similar constructors too
    function __construct($id_number) {
        // Do more database stuff in here...
    }

    // Various functions specific to this class
    // Some functions in common with other classes
}

问题是有很多这样的类,它们都需要有类似的构造函数和一些常见的函数,所以我理想情况下希望编写一个父类(super class)来处理所有这些东西,以便最小化复制/粘贴在。然而,每个子类都有不同的实例变量和参数,那么设计父类(super class)的最佳方式是什么?

(也许更好地说,如何编写构造函数或其他函数来处理类的实例变量,但不一定知道类的实例变量是什么并按名称对它们进行硬编码?)

最佳答案

您可以通过多种方式实现非常通用的“实体”类型类,尤其是您利用各种魔术方法。

考虑这样的类(只是一些类似实体类共享的随机便捷方法):

<?php
abstract class AbstractEntity {

  protected $properties;

  public function setData($data){
    foreach($this->properties as $p){
        if (isset($data[$p])) $this->$p = $data[$p];
    }
  }

  public function toArray(){
    $array = array();
    foreach($this->properties as $p){
       $array[$p] = $this->$p;
       //some types of properties might get special handling
       if ($p instanceof DateTime){
           $array[$p] = $this->$p->format('Y-m-d H:i:s');
       }
    }
  }

  public function __set($pname,$pvalue){
     if (! in_array($pname,$this->properties)){
        throw new Exception("'$pname' is not a valid property!");
     }
     $this->$pname = $pvalue;
  }
}


<?php

class Person extends AbstractEntity {
   protected $properties = array('firstname','lastname','email','created','modified');
}

关于php - OOP 设计问题 - 避免在类似的类中重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4413771/

相关文章:

while 循环中的 Javascript。这是可以接受的做法吗?

php - 合并图像 PHP

delphi - 如何在Delphi中支持接口(interface)定义中的类方法

PHP CURL 什么都不返回

php - MySQL转换字符集问题

c++ - 抽象类不直接映射,有什么优雅的解决方案吗?

javascript - 为什么有些方法会就地修改调用对象而其他方法会返回要分配的值?

java - 从 super 对象创建子对象

design-patterns - 工厂模式问题

ruby-on-rails - 在 Rails 中的何处放置创建模型和关联逻辑?