The Typed Data API was created to provide developers with a consistent way of interacting with data in different ways. Not only does the API allow you to interact with the actual data, it also provides means of fetching more information, or metadata, about the actual data.
The Typed Data API is a low level, generic and reusable object oriented API that appears at multiple levels of the Drupal 8 architecture. Take for example, the EntityAdapter, which extends TypedData and acts as a wrapper for an Entity. Or FieldItemBase, which is an unwrapped extension of TypedData.
Why do we need the Typed Data API?
Unlike many other languages, PHP is a very loosely typed language. It doesn’t have a clear definition of the different types of data it deals with. Therefore Drupal used to be the same. For example, there was no consistent way of telling if a field value is a string, an integer or a timestamp. Or even, to tell if something is translatable or accessible (as in permissions). Even if you as a developer happen to know that the value of a text field happens to be a string, there’s no consistent programmatic way of fetching this information. This creates a lot of problems when building machine readable APIs on Drupal that exposes its data to other systems.
There needs to be a consistent way of typing this data, or describing the data.
The basic API
The Typed Data API mainly provides three different interfaces. Below you will find a description of these interfaces and some important methods (not a comprehensive list).
Implementations of this interface are used for data that is composed of named properties with more pieces of data. This interface defines some basic methods, including:
Fetch the value of a property.
Set the value of a property. $value must be an instance of one of the these three interfaces.
Implementations of this interface are used for something that is composed of a sequential list of other things, for instance a list of other complex pieces of data. Lists are ordered and may contain duplicate items, e.g. a multiple node reference field could contain the same reference two times.
This interface extends the
Method inherited from ArrayAccess, so individual items may be retrieved as from arrays:
$first_item = $items;
Implementations of this interface are used for something that represents a single piece of typed data, like a string, integer etc. This is the smallest building block in the Typed Data API, and it can definitely be used as is. The interface defines some basic methods, including:
Fetches the value of the data.
Sets the value of the data.
Fetches information about the data telling you if it’s of a primitive type etc.
Using the API
[To be done]
What a definition looks like
[To be done]
The Drupal 8 entity API is built on the Typed Data API.