class EntityAffiliateCampaign extends Entity {
public function __construct(array $values = array(), $entityType = NULL) {
// Add default values, if they are not set.
$values += array(
'name' => '',
'affiliate_uid' => 0,
'is_default' => FALSE,
);
parent::__construct($values, 'affiliate_campaign');
}
}
That's my entity class. It initializes some important values so that I don't get an empty object from entity_create().
However, this gives me a problem with entity_load, because the entity controller does this:
$result->setFetchMode(PDO::FETCH_CLASS, $this->entityInfo['entity class'], array(array(), $this->entityType));
What this line of code does is prefill an object from the database values, THEN calls it's constructor.
And the default entity class constructor does this:
// Set initial values.
foreach ($values as $key => $value) {
$this->$key = $value;
}
Thus overwriting the already set values, and giving me an empty object.
Attaching a sensible patch.
This could also be a support request if you think I'm doing the whole defaults thing wrong :P
Comments
Comment #1
damien tournoud commentedThis patch allows using the $values array to let the constructor set default values. It bends the original intend of $values, but it makes sense to me.
Comment #2
fagoI don't think we can do that, as this would break passing in values for existing implementations that use entity object properties with defined defaults. Any cause you aren't just defining a (public) object property with a default value? As PHP has already a solution for property defaults, I don't think we have to reinvent the wheel.
Comment #3
bojanz commentedAs I said:
The current approach made sense to me because we did the same in various controllers...
Should we "won't fix" this then, and document the preferred way somewhere?
Comment #4
fagoYep, let's document that. Maybe in the docblock of the Entity class?
Comment #5
bojanz commentedMaybe like this? Not sure how clear it is.
Definitely needed though, the same confusion popped up at http://drupal.org/project/model.
Comment #6
fagoThanks, I tried to further improve it. That should help I think?
Comment #7
bojanz commentedYes, that's better.
Comment #8
fagoThat was quick ;)
Thanks, committed.