views:

95

answers:

1

I have a model class (obviously, it extends Doctrine_Record) that "acts as" a custom template.

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?

A: 

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.

tilman
I am talking about Doctrine behaviors, not the model classes themselves. I want to add a virtual field (like "virtual_field" in your example) to more than one model at once by putting the functionality into a template class (which is part of a behavior).
mattalexx
Ok. I think now I understand what you are trying to do. You want to override Doctrine_Record::__get() from a Doctrine_Template, is that right? Now, that's a tough one ;) Disregard my answr then, sorry.
tilman