Field / FieldItem classes need to access their own FieldDefinition.
The waters are muddied by the fact that base fields do not have a FieldDefinition object yet -
#2047229: Make use of classes for entity field and data definitions β
Configurable fields (ConfigField / ConfigFieldItem) have special code that fetches the FieldDefinition object from config based on the field name & entity type + bundle. There is a hackish workaround to be able to inject a bespoke FieldDefinition ($instance in that case) into the constructor of ConfigField / ConfigFieldItem.
But there are cases where we need that FieldDefinition to not be the "official one stored in code or config":
- use a "variant" of a field definition (e.g non-'required' even if the "real" field is 'required', for "default value" input in Field UI)
- use a field that has been deleted and is not in config anymore (field purge)
- use a field definition that doesn't officially exist yet (Field UI currently has to create the field+instance the moment you submit the first step, and then lets you edit them, instead of creating them after the last step)
Having the objects fetch their FieldDefinitions from the outside, as we well know in D8, is an antipattern, the definitions should be injected into them by the outside code. Typically, it should be the code that creates the Field / FieldItem objects in an entity that reads field definitions from config.
Challenges:
- Field / FieldItem objects are instanciated by the TypedDataFactory, which constrains the arguments of their __construct(). This factory currently injects the "typed data" definition *array* (hook_entity_field_info()), that is way incomplete and is not what the rest of the Field / FieldItem classes use.
- Even if we sort out the factory / instantiation flow to inject a FieldDefinition instead of an array, this will let us create standalone Field / FieldItem objects with a custom FieldDefinition - which is fine -, but still doesn't let us put it in an actual entity. There is currently no way to place an arbitrary Field object in an entity, you can only assign *values* into the Field objects that are already there.