开发者

Doctrine 1.2: Overriding Doctrine_Record::__get() from a template

I have a model class (obviously, it extends Doctrine_Record) that "acts as" a custom templa开发者_运维问答te.

I want to get values like this: "echo $record->virtual_field". Is there a way to override the getter method in my custom template to provide a custom response, then either pass on the request to the parent class or not?

In other words, is there a way to override Doctrine_Record::__get() from a related template?


Ok. I assume you're not talking about actual Behaviour 'actAs' Templates.

If you define a new __get() method, it will automatically override the parent's __get() method.

Now in your new __get() method, you first check if it exists in your current instance, and then the parent's.

I hacked this together (bear in mind, it's almost midnight):

<?php
class bar {
public $data = array();
  public function __construct() {
    $this->data['virtual_field'] = "set in bar";
  }

  public function  __get($name) {
    if(array_key_exists($name, $this->data)) {
      return $this->data[$name];
    }
    return null;
  }

  public function __set($name, $value) {
    $this->data[$name] = $value;
  }
}

class foo extends bar {
public $data = array();
  public function __construct() {

  }

  public function  __get($name) {
    if(array_key_exists($name, $this->data)) {
      return $this->data[$name];
    }
    if (parent::__get($name))
      return parent::__get($name);

    return null;
  }

  public function __set($name, $value) {
    $this->data[$name] = $value;
  }
}

$a = new foo;
echo $a->virtual_field;

Now I dont know how well this works for what you are trying to achieve.


class Product extends Doctrine_Record {

    //...

    public function __get($name) {
        if ($name == 'virtual_field') {
            return $this->virtual_field();
        }                                                     
        else {
            return parent::__get($name);
        }
    }


    public function virtual_field() {
        // calculate or retrieve virtual field value
        return $value;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜