What is the best way to add a derived field to a subclass of Doctrine_Record?

Imagine that I have a table called "element" in which there is a column "price". In addition to the full price, I would like to receive a price quote after 12 months, i.e.

class Item extends Doctrine_Record { ... public function getMonthlyPrice() { return $this->price/12; } } 

Now, let's say, I would like the Item action as a monthly price to be just another column, and not a function call, for example,

 $m = Doctrine_Core::getTable("Item")->find(1); echo $m->price; //prints 120 echo $m->monthlyPrice; //prints 10 

My first instinct is to override the __get () method. Is there a better or more standard way to do this in the Doctrine?


Bonus question:

Is there some very smart way that I can set an object, so when I do

 var_dump($m->getData()) 

I see

 array 'price' => 120 'monthlyPrice' => 10 

It will be pretty elegant.

+4
source share
2 answers

Since Brian said you can do this with filters, but there is another way that I think is closer to what you are looking for - you need to enable the Doctrine function ATTR_AUTO_ACCESSOR_OVERRIDE, which means that it will check the methods in the get * form and set *, which match your property, call them automatically. Here is an example:

 class Example extends Doctrine_Record { public function getFoo() { return 'foo'; } } Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, true); $example = new Example(); echo $example->foo; 

As for the second part of your question, but not what I saw, it is best to override the method in your models or create a subclass of Doctrine_Record that will then extend your models, which has one override that completes this functionality.

0
source

I think you need Record Filters. I really don't know the Doctrine, I primarily use Propel; but it looks like it can accomplish what you need:

http://www.doctrine-project.org/projects/orm/1.2/docs/manual/defining-models/pl#record-filters

+1
source

Source: https://habr.com/ru/post/1336223/


All Articles