I saw a very good presentation on entities. Here are some ways to access field properties on entities in Drupal:
// Complete
$entity->get('field')->get(0)->get('property')->getValue();
// Array access
$entity->get('field')[0]->get('property')->getValue();
// __get() for properties equals ->get('property)->getValue();
$entity->get('field')[0]->property;
// Delta 0 is the default for properties when using __get()
$entity->get('field')->property;
// Complete
$entity->get('field')->get(0)->get('property')->setValue('myvalue');
// Magic
$entity->get('field')->property = 'myvalue';
// ContentEntityInterface::set(), single/main property.
$entity->set('field', 'myvalue');
// ContentEntityInterface::set(), multiple properties.
$node->set('body', ['value' => 'Hello', 'format' => 'plain_text']);
// ContentEntityInterface::set(), multiple items.
$user->set('roles', ['content_editor', 'administrator']);
// Append an item.
$user->get('roles')->appendItem('administrator');
getValue()
// On a field item.
$user->get('roles')[0]->get('target_id')->getValue()
=> "content_editor"
// On a field item.
$user->get('roles')[0]->getValue();
=> ["target_id" => "content_editor"]
// On a field.
$user->get('roles')->getValue();
=> [
0 => ["target_id" => "content_editor"],
1 => ["target_id" => "administrator"],
]
// Shorthand, get a single property of all items.
array_column($user->get('roles')->getValue(), 'target_id')
=> ["content_editor", "administrator"]
// Loop over all fields of an entity.
foreach ($entity as $field_name => $field) {
// Loop over all items of a field.
foreach ($field as $item) {
if ($item->entity) {
}
}
}
Full presentation: https://berdir.github.io/entities-explained