我正在用 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/