Ans*_*ala 2 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
}
Run Code Online (Sandbox Code Playgroud)
问题是有很多这样的类,它们都需要有类似的构造函数和一些通用函数,所以我理想地希望编写一个超类来处理所有这些东西,以便最大限度地减少复制/粘贴。然而,每个子类都有不同的实例变量和参数,那么设计超类的最佳方式是什么?
(也许更好地说,如何编写构造函数或其他函数来处理类的实例变量,但不一定知道类的实例变量是什么并按名称对它们进行硬编码?)
您可以通过多种方式实现非常通用的“实体”类型类,尤其是您利用各种魔术方法。
考虑这样的类(只是一些类似实体的类共享的随机便捷方法):
<?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');
}
Run Code Online (Sandbox Code Playgroud)