FieldConfigInterface::setDefaultValueCallback() accepts a callback for a base of config field's default value, either as a function or method name.
We get this pattern repeated by entity types over and over again for fields where the default value comes from a service, such as the uid and created fields:
Node entity:
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Authored by'))
->setDescription(t('The username of the content author.'))
->setRevisionable(TRUE)
->setSetting('target_type', 'user')
->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')
...
public static function getCurrentUserId() {
return [\Drupal::currentUser()->id()];
}
Media entity:
$fields['uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Authored by'))
->setDescription(t('The user ID of the author.'))
->setRevisionable(TRUE)
->setDefaultValueCallback(static::class . '::getCurrentUserId')
...
$fields['created'] = BaseFieldDefinition::create('created')
->setLabel(t('Authored on'))
->setDescription(t('The time the media item was created.'))
->setTranslatable(TRUE)
->setRevisionable(TRUE)
->setDefaultValueCallback(static::class . '::getRequestTime')
...
public static function getCurrentUserId() {
return [\Drupal::currentUser()->id()];
}
public static function getRequestTime() {
return \Drupal::time()->getRequestTime();
}
We could remove these wrapper method and save on repeated code and improve DX if we allow setDefaultValueCallback() to accept a callback in service notation the same way that route controllers do, that is, 'service_name:method'.