1

现在我有一个对 DB 执行 ORM 的 BaseObject。我依靠私有 $data 和魔术 setter 和 getter 来创建具有一堆列作为私有对象成员的对象(动态)。在子类中,如果我想更改行为以设置单个对象成员,我必须覆盖父 setter 并查找密钥。我的问题是是否有更好的方法来做到这一点,我可以覆盖单个对象成员而不是通过 __setter

映射到数据库并动态创建一堆私有参数的基本对象映射器

class Base
 {
    private $data = array();

    public function __construct(){
        //get columns info from db and do set
    }
    public function __set($key, $value){
        $this->data[$key] = $value;        
    }

   public function __get($key){
       return isset($this->data[$key])? $this->data[$key] : null;       
   }
}

和儿童班。现在要覆盖参数设置我必须这样做

 class Child extends Base
 {
     public function __set($name, $value){
        if($name == 'dog' && $value == 'chihuahua')
          $this->dog = 'dog bark wolf wolf';
        else if($name == 'cat' && $value == 'sand')
          $this->cat = 'cat say meow meow';
       ...
     }
 }

我的问题是有优雅的方法来做到这一点,也许是在儿童班上这样的?

public function __set_dog($value)
    $this->dog = 'dog bark wolf wolf';

public function __set_cat($value)
   $this->cat = 'cat say meow meow';

目标是做

$animal1 = new Animal();
$anmial1->dog = 'pit bull';
$anmial1->cat= 'sand';

$animal2 = new Animal();
$anmial1->dog = 'chihuahua';
$anmial1->cat= 'house cat';
4

1 回答 1

5

您可以动态检查是否存在常规命名的 getter/setter 方法并调用它而不是返回 $data 成员。这是一个例子:

class Base {
    public function __get($key) {
        if (method_exists($this, $method = 'get' . ucfirst($key))) {
           return $this->$method($key);
        } else {
           return isset($this->data[$key])? $this->data[$key] : null;
        }
    }

    public function __set($key, $value) {
        if (method_exists($this, $method = 'set' . ucfirst($key))) {
           $this->$method($key, $value);
        } else {
           $this->data[$key] = $value;
        }
    }
}

class Animal extends Base {
    protected $data = array('fish' => 'blublublub', 'dog' => 'woof', 'cat' => 'meow');

    public function getDog() {
        return 'dog bark wolf wolf';
    }

    public function getCat() {
        return 'cat say meow meow';
    }
}

$animal = new Animal();
echo $animal->fish; // "blublublub"
echo $animal->dog; // "dog bark wolf wolf"
echo $animal->cat; // "cat say meow meow"
于 2012-10-23T20:36:55.290 回答