[DX] Simplify getting and setting of values without using the 'und' data structure in entities
One of the things I really hated about the change from D6 to D7 was the increase in complexity of the data structures in core. In particular, sites that did not need translation now had to deal with this extra und key everywhere.
There are many ways we can simplify the data structure in Backdrop without limiting functionality. Let's use this issue to talk about some of those options, and make a plan for Backdrop 2.
I agree. Despite my philosophical qualms, I've actually started using Entity Metadata Wrappers all the time in D7 since it is much easier to just call $entity->field_something->value() than $entity->field_something['und'][0].
However, without the ['und'] or complicated accessor functions, how would the field arrays work with multilingual sites?
something like:
$node->changeLanguage('es');
$node->field...
Well, right now there is a 1-to-1 relationship between how the values are stored in the node and where they can be accessed as an array. As soon as you start programmatically changing the language available in the field value array, the values for other languages would have to be stored somewhere else, and then it is confusing how updating a field value in the array would affect the internal storage.
Perhaps we should just add a value accessor function to the entity classes, so you can call something like:
$entity->value('field_something');
$entity->value('field_something', 'es');
That's a good idea. We could even have a getValue and setValue so people wouldn't even need to know about that crazy array structure.
Yeah, and adding accessor functions wouldn't need to wait until 2.x.
The one downside with passing the field name into the accessor functions, is it would not allow for the chaining that is provided by Entity Metadata Wrappers, where you can use something like:
$wrapper->author->mail->set('[email protected]');
As part of the reference module work, we should look at what it would look like to follow the reference data structures to get related entites and their values.
It looks like the ContentEntityBase class in D8 provides similar get and set functions: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21ContentEntityBase.php/function/ContentEntityBase%3A%3Aget/8.2.x https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!ContentEntityBase.php/function/ContentEntityBase%3A%3Aset/8.2.x
We should look at that class, and the FieldableEntityInterface it is inheriting from, to see how they implemented things in D8.
There's also a more performant alternative to Entity Metadata Wrappers available as a Drupal 7 contrib project: https://www.drupal.org/project/field_extract
I think this came up recently as something that "feels missing" from the Backdrop core enitty API.