SlideShare a Scribd company logo
Typed Data
in Drupal 8
Drupal Cafe Kiev - 22.12.16
hello!
I am Igor Karpilenko
Drupal developer from Deweb studio
https://www.drupal.org/u/hamrant
https://www.facebook.com/hamrant
https://www.linkedin.com/in/hamrant
Prehistory
The problem
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.
Typed Data
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.
Each data type in the Typed Data API is a plugin class (annotation class
example: DrupalCoreTypedDataAnnotationDataType).
These plugins are managed by the typed_data_manager service (by
default DrupalCoreTypedDataTypedDataManager).
Each data object encapsulates a single piece of data, provides access
to the metadata, and provides validation capability.
Where to look?
core/lib/Drupal/Core/TypedData
The Typed Data API interfaces
List
Data
Primitive
Data
Complex
Data
Primitive Data
Implementations of this interface are used for something that
represents a single piece of typed data, like a string or integer.
This is the smallest building block in the Typed Data API.
BinaryData
BooleanData
Email
FloatData
IntegerData
StringData
DateTimeIso8601 - DateTimeInterface
DurationIso8601 - DurationInterface
TimeSpan - DurationInterface
Timestamp - DateTimeInterface
Primitive data types
PrimitiveInterface methods
getValue() - Gets the primitive data value
setValue($value) - Sets the primitive data value
getCastedValue() - Gets the primitive data value casted to the
correct PHP type
Primitive data type example
/**
* The integer data type.
*
* The plain value of an integer is a regular PHP integer. For setting the value
* any PHP variable that casts to an integer may be passed.
*
* @DataType(
* id = "integer",
* label = @Translation("Integer")
* )
*/
class IntegerData extends PrimitiveBase implements IntegerInterface
/**
* {@inheritdoc}
*/
public function getCastedValue() {
return (int) $this->value;
}
}
create a typed data object in code
First get the typed_data_manager service from the container or by
calling Drupal::typedDataManager().
Then pass the plugin ID to $manager::createDataDefinition() to
create an appropriate data definition object.
Then pass the data definition object and the value of the data to
$manager::create() to create a typed data object.
$definition = DataDefinition::create('integer');
$int = Drupal::typedDataManager()->create($definition);
$int->setValue('10');
$validation = $int->validate();
$raw_data = $int->getValue();
$int_data = $int->getCastedValue();
$raw_data_type = gettype($raw_data);
$int_data_type = gettype($int_data);
Integer data type usage example
Constraints
The Data Definition class can set constraints upon the Typed Data
object.
Constraint plugins:
core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint
Symfony constraints:
docroot/vendor/symfony/validator/Constraints
Constraints plugins:
AllowedValues
ComplexData
Count
Email
Null
Length
NotNull
PrimitiveType
Range
Regex
UniqueField
Symfony constraints:
Blank
Callback
CardScheme
Choice
Collection
Count
Country
Currency
Date
EqualTo
File
GreaterThan
Image
Url
etc...
/**
* Email constraint.
*
* Overrides the symfony constraint to use the strict setting.
*
* @Constraint(
* id = "Email",
* label = @Translation("Email", context = "Validation")
* )
*/
class EmailConstraint extends Email {
public $strict = TRUE;
/**
* {@inheritdoc}
*/
public function validatedBy() {
return 'SymfonyComponentValidatorConstraintsEmailValidator';
}
}
Constraints usage example
$definition = DataDefinition::create('string');
$definition->addConstraint('Regex', '/^([0-9]{4}-){3}[0-9]{4}/');
$credit_card = Drupal::typedDataManager()->create($definition);
$credit_card->setValue('yg65-g67dlkj8-9879'); // Invalid value.
$validation1 = $credit_card->validate();
$credit_card->setValue('1250-5154-6548-6848'); // Valid value.
$validation2 = $credit_card->validate();
List data types represent data that is an ordered list of typed data, all of
the same type.
More precisely, the plugins in the list must have the same base plugin ID;
however, some types (for example field items and entities) are provided
by plugin derivatives and the sub IDs can be different.
List Data types
ListInterface methods
getDataDefinition()
isEmpty()
getItemDefinition()
get($index)
set($index, $value)
first()
appendItem($value = NULL)
removeItem($index)
filter($callback)
List data example
$data = [
'1250-5154-6548-6831',
'2233-5154-6648-6843',
'3276-5154-6748-6822',
'4289-5154-6848-6867',
];
$list_definition = ListDataDefinition::create('string');
$credit_cards = Drupal::typedDataManager()->create($list_definition);
$credit_cards->setValue($data);
$validation = $credit_cards->validate();
$first_card = $credit_cards->get(0)->getValue();
foreach ($credit_cards as $card) {
$test[] = $card->getValue();
}
Complex Data
Complex data types, with interface
DrupalCoreTypedDataComplexDataInterface, represent data with
named properties.
The properties can be accessed with get() and set() methods. The value
of each property is itself a typed data object, which can be primitive,
complex, or list data.
The "map" data type
The "map" data type represent a simple complex data type, e.g. for
representing associative arrays. It can also serve as base class for any
complex data type.
By default there is no metadata for contained properties. Extending
classes may want to override
MapDataDefinition::getPropertyDefinitions() to define it.
Defining data types
Create a Definition class that implements one of the Typed Data
interfaces.
Create a DataType plugin that use your Definition class .
To do that, put it in namespace
DrupalyourmodulePluginDataType, and add annotation of type
DrupalCoreTypedDataAnnotationDataType to the
documentation header.
<?php
namespace Drupalactivenet_syncTypedDataDefinition;
use DrupalCoreTypedDataComplexDataDefinitionBase;
use DrupalCoreTypedDataDataDefinition;
/**
* ActiveNet Asset Price definition.
*/
class AssetPriceDefinition extends ComplexDataDefinitionBase {
/**
* {@inheritdoc}
*/
public function getPropertyDefinitions() {
if (!isset($this->propertyDefinitions)) {
$info = &$this->propertyDefinitions;
$info['priceType'] = DataDefinition::create('string')->setRequired(TRUE)->setLabel('priceType');
$info['priceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('priceAmt');
$info['maxPriceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('maxPriceAmt');
$info['minPriceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('minPriceAmt');
}
return $this->propertyDefinitions;
}
}
activenet_sync/src/TypedData/Definition/AssetPriceDefinition.php
<?php
namespace Drupalactivenet_syncPluginDataType;
use DrupalCoreTypedDataPluginDataTypeMap;
/**
* Asset Price type.
*
* @DataType(
* id = "asset_price",
* label = @Translation("Asset price"),
* definition_class = "Drupalactivenet_syncTypedDataDefinitionAssetPriceDefinition"
* )
*/
class AssetPrice extends Map {}
activenet_sync/src/Plugin/DataType/AssetPrice.php
$data = [
'priceType' => 'test',
'priceAmt' => 100,
'maxPriceAmt' => 120,
'minPriceAmt' => 100,
];
$price_definition = AssetPriceDefinition::create('asset_price');
$price = Drupal::typedDataManager()->create($price_definition);
$price->setValue($data);
$validation = $price->validate();
$min = $price->get('minPriceAmt')->getValue();
Using data types
In the Field API, data types can be
used as the class in the property
definition of the field.
Describe data defined elsewhere i.e.
schemas from external systems.
In configuration schema files, you can
use the unique ID ('id' annotation)
from any DataType plugin class as the
'type' value for an entry.
paragraphs.paragraphs_type.*:
type: config_entity
label: 'Paragraphs type config'
mapping:
id:
type: string
label: 'ID'
label:
type: label
label: 'Label'
YMCA Seattle
Typed Data Explorer
Simple module to browse Typed Data.
https://github.com/wellnet/typed_data_explorer
Links
https://api.drupal.org/api/drupal/core%21core.api.php/group/typed_data/8.2.x
https://www.drupal.org/node/1794140
https://www.sitepoint.com/drupal-8-entity-validation-and-typed-data-explained/
https://www.sitepoint.com/drupal-8-entity-validation-and-typed-data-demonstration/
https://www.youtube.com/watch?v=P49GOFQhKlQ
http://lussoluca.github.io/DDD-2016 - slides from the above video
https://www.youtube.com/watch?v=v7m6qOxH1t0
http://softpixel.com/~mradcliffe/files/dcatl2015-typeddata.pdf - slides from the above
video
https://www.drupal.org/project/xero
Thanks for your attention!

More Related Content

What's hot

Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
Aijaz Ali Abro
 
Actualizacion de base de datos desde Visual Basic
Actualizacion de base de datos desde Visual Basic Actualizacion de base de datos desde Visual Basic
Actualizacion de base de datos desde Visual Basic
EduardoMontiel18
 
Oracle APEX Cheat Sheet
Oracle APEX Cheat SheetOracle APEX Cheat Sheet
Oracle APEX Cheat Sheet
Dimitri Gielis
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
Reem Alattas
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
WebStackAcademy
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
NexThoughts Technologies
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
Sachin G Kulkarni
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
Kang-min Liu
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
Jim Yeh
 
"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGapChristian Rokitta
 
Deploying PHP applications with Phing
Deploying PHP applications with PhingDeploying PHP applications with Phing
Deploying PHP applications with Phing
Michiel Rook
 
Jetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning TourJetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning Tour
Matthew Clarke
 
Le Wagon - React 101
Le Wagon - React 101Le Wagon - React 101
Le Wagon - React 101
Sébastien Saunier
 
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Svelte JS introduction
Svelte JS introductionSvelte JS introduction
Svelte JS introduction
Mikhail Kuznetcov
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
Christian Heilmann
 

What's hot (20)

Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
Actualizacion de base de datos desde Visual Basic
Actualizacion de base de datos desde Visual Basic Actualizacion de base de datos desde Visual Basic
Actualizacion de base de datos desde Visual Basic
 
Oracle APEX Cheat Sheet
Oracle APEX Cheat SheetOracle APEX Cheat Sheet
Oracle APEX Cheat Sheet
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap"Native" Apps with APEX and PhoneGap
"Native" Apps with APEX and PhoneGap
 
Deploying PHP applications with Phing
Deploying PHP applications with PhingDeploying PHP applications with Phing
Deploying PHP applications with Phing
 
Jetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning TourJetpack Compose - A Lightning Tour
Jetpack Compose - A Lightning Tour
 
Le Wagon - React 101
Le Wagon - React 101Le Wagon - React 101
Le Wagon - React 101
 
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
(WPF교육)ListBox와 Linq 쿼리를 이용한 간단한 데이터바인딩, 새창 띄우기, 이벤트 및 델리게이트를 통한 메인윈도우의 ListB...
 
Svelte JS introduction
Svelte JS introductionSvelte JS introduction
Svelte JS introduction
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 

Similar to Typed data in drupal 8

Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
Tomas Petricek
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
Randy Connolly
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
Zsolt Tasnadi
 
Introduction to Data Science With R Notes
Introduction to Data Science With R NotesIntroduction to Data Science With R Notes
Introduction to Data Science With R Notes
LakshmiSarvani6
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
Alexander Varwijk
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
Mahmoud Ouf
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
Software Park Thailand
 
Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)eddiejaoude
 
Boost Your Development With Proper API Design
Boost Your Development With Proper API DesignBoost Your Development With Proper API Design
Boost Your Development With Proper API Design
MarcusHeld1
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
facebookrecovery1
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
Mahmoud Ouf
 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastore
Haris Khan
 
Migrating data into Drupal using the migrate module
Migrating data into Drupal using the migrate moduleMigrating data into Drupal using the migrate module
Migrating data into Drupal using the migrate module
Johan Gant
 
Lesson 2 data preprocessing
Lesson 2   data preprocessingLesson 2   data preprocessing
Lesson 2 data preprocessing
AbdurRazzaqe1
 
Data Wrangling and Visualization Using Python
Data Wrangling and Visualization Using PythonData Wrangling and Visualization Using Python
Data Wrangling and Visualization Using Python
MOHITKUMAR1379
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Vitaly Gordon
 

Similar to Typed data in drupal 8 (20)

Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#Accessing loosely structured data from F# and C#
Accessing loosely structured data from F# and C#
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 
WPF and Databases
WPF and DatabasesWPF and Databases
WPF and Databases
 
Introduction to Data Science With R Notes
Introduction to Data Science With R NotesIntroduction to Data Science With R Notes
Introduction to Data Science With R Notes
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)Models Best Practices (ZF MVC)
Models Best Practices (ZF MVC)
 
Field api.From d7 to d8
Field api.From d7 to d8Field api.From d7 to d8
Field api.From d7 to d8
 
Boost Your Development With Proper API Design
Boost Your Development With Proper API DesignBoost Your Development With Proper API Design
Boost Your Development With Proper API Design
 
Csharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptxCsharp_dotnet_ADO_Net_database_query.pptx
Csharp_dotnet_ADO_Net_database_query.pptx
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastore
 
Migrating data into Drupal using the migrate module
Migrating data into Drupal using the migrate moduleMigrating data into Drupal using the migrate module
Migrating data into Drupal using the migrate module
 
Lesson 2 data preprocessing
Lesson 2   data preprocessingLesson 2   data preprocessing
Lesson 2 data preprocessing
 
Data Wrangling and Visualization Using Python
Data Wrangling and Visualization Using PythonData Wrangling and Visualization Using Python
Data Wrangling and Visualization Using Python
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedIn
 

Recently uploaded

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 

Recently uploaded (20)

Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 

Typed data in drupal 8

  • 1. Typed Data in Drupal 8 Drupal Cafe Kiev - 22.12.16
  • 2. hello! I am Igor Karpilenko Drupal developer from Deweb studio https://www.drupal.org/u/hamrant https://www.facebook.com/hamrant https://www.linkedin.com/in/hamrant
  • 4. The problem 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.
  • 5. Typed Data 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.
  • 6. 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.
  • 7. Each data type in the Typed Data API is a plugin class (annotation class example: DrupalCoreTypedDataAnnotationDataType). These plugins are managed by the typed_data_manager service (by default DrupalCoreTypedDataTypedDataManager). Each data object encapsulates a single piece of data, provides access to the metadata, and provides validation capability.
  • 9. The Typed Data API interfaces List Data Primitive Data Complex Data
  • 10. Primitive Data Implementations of this interface are used for something that represents a single piece of typed data, like a string or integer. This is the smallest building block in the Typed Data API.
  • 11. BinaryData BooleanData Email FloatData IntegerData StringData DateTimeIso8601 - DateTimeInterface DurationIso8601 - DurationInterface TimeSpan - DurationInterface Timestamp - DateTimeInterface Primitive data types
  • 12. PrimitiveInterface methods getValue() - Gets the primitive data value setValue($value) - Sets the primitive data value getCastedValue() - Gets the primitive data value casted to the correct PHP type
  • 13. Primitive data type example /** * The integer data type. * * The plain value of an integer is a regular PHP integer. For setting the value * any PHP variable that casts to an integer may be passed. * * @DataType( * id = "integer", * label = @Translation("Integer") * ) */ class IntegerData extends PrimitiveBase implements IntegerInterface /** * {@inheritdoc} */ public function getCastedValue() { return (int) $this->value; } }
  • 14. create a typed data object in code First get the typed_data_manager service from the container or by calling Drupal::typedDataManager(). Then pass the plugin ID to $manager::createDataDefinition() to create an appropriate data definition object. Then pass the data definition object and the value of the data to $manager::create() to create a typed data object.
  • 15. $definition = DataDefinition::create('integer'); $int = Drupal::typedDataManager()->create($definition); $int->setValue('10'); $validation = $int->validate(); $raw_data = $int->getValue(); $int_data = $int->getCastedValue(); $raw_data_type = gettype($raw_data); $int_data_type = gettype($int_data); Integer data type usage example
  • 16.
  • 17. Constraints The Data Definition class can set constraints upon the Typed Data object. Constraint plugins: core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint Symfony constraints: docroot/vendor/symfony/validator/Constraints
  • 19. /** * Email constraint. * * Overrides the symfony constraint to use the strict setting. * * @Constraint( * id = "Email", * label = @Translation("Email", context = "Validation") * ) */ class EmailConstraint extends Email { public $strict = TRUE; /** * {@inheritdoc} */ public function validatedBy() { return 'SymfonyComponentValidatorConstraintsEmailValidator'; } }
  • 20. Constraints usage example $definition = DataDefinition::create('string'); $definition->addConstraint('Regex', '/^([0-9]{4}-){3}[0-9]{4}/'); $credit_card = Drupal::typedDataManager()->create($definition); $credit_card->setValue('yg65-g67dlkj8-9879'); // Invalid value. $validation1 = $credit_card->validate(); $credit_card->setValue('1250-5154-6548-6848'); // Valid value. $validation2 = $credit_card->validate();
  • 21.
  • 22. List data types represent data that is an ordered list of typed data, all of the same type. More precisely, the plugins in the list must have the same base plugin ID; however, some types (for example field items and entities) are provided by plugin derivatives and the sub IDs can be different. List Data types
  • 24. List data example $data = [ '1250-5154-6548-6831', '2233-5154-6648-6843', '3276-5154-6748-6822', '4289-5154-6848-6867', ]; $list_definition = ListDataDefinition::create('string'); $credit_cards = Drupal::typedDataManager()->create($list_definition); $credit_cards->setValue($data); $validation = $credit_cards->validate(); $first_card = $credit_cards->get(0)->getValue(); foreach ($credit_cards as $card) { $test[] = $card->getValue(); }
  • 25.
  • 26. Complex Data Complex data types, with interface DrupalCoreTypedDataComplexDataInterface, represent data with named properties. The properties can be accessed with get() and set() methods. The value of each property is itself a typed data object, which can be primitive, complex, or list data.
  • 27. The "map" data type The "map" data type represent a simple complex data type, e.g. for representing associative arrays. It can also serve as base class for any complex data type. By default there is no metadata for contained properties. Extending classes may want to override MapDataDefinition::getPropertyDefinitions() to define it.
  • 28. Defining data types Create a Definition class that implements one of the Typed Data interfaces. Create a DataType plugin that use your Definition class . To do that, put it in namespace DrupalyourmodulePluginDataType, and add annotation of type DrupalCoreTypedDataAnnotationDataType to the documentation header.
  • 29. <?php namespace Drupalactivenet_syncTypedDataDefinition; use DrupalCoreTypedDataComplexDataDefinitionBase; use DrupalCoreTypedDataDataDefinition; /** * ActiveNet Asset Price definition. */ class AssetPriceDefinition extends ComplexDataDefinitionBase { /** * {@inheritdoc} */ public function getPropertyDefinitions() { if (!isset($this->propertyDefinitions)) { $info = &$this->propertyDefinitions; $info['priceType'] = DataDefinition::create('string')->setRequired(TRUE)->setLabel('priceType'); $info['priceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('priceAmt'); $info['maxPriceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('maxPriceAmt'); $info['minPriceAmt'] = DataDefinition::create('float')->setRequired(TRUE)->setLabel('minPriceAmt'); } return $this->propertyDefinitions; } } activenet_sync/src/TypedData/Definition/AssetPriceDefinition.php
  • 30. <?php namespace Drupalactivenet_syncPluginDataType; use DrupalCoreTypedDataPluginDataTypeMap; /** * Asset Price type. * * @DataType( * id = "asset_price", * label = @Translation("Asset price"), * definition_class = "Drupalactivenet_syncTypedDataDefinitionAssetPriceDefinition" * ) */ class AssetPrice extends Map {} activenet_sync/src/Plugin/DataType/AssetPrice.php
  • 31. $data = [ 'priceType' => 'test', 'priceAmt' => 100, 'maxPriceAmt' => 120, 'minPriceAmt' => 100, ]; $price_definition = AssetPriceDefinition::create('asset_price'); $price = Drupal::typedDataManager()->create($price_definition); $price->setValue($data); $validation = $price->validate(); $min = $price->get('minPriceAmt')->getValue();
  • 32.
  • 33. Using data types In the Field API, data types can be used as the class in the property definition of the field. Describe data defined elsewhere i.e. schemas from external systems. In configuration schema files, you can use the unique ID ('id' annotation) from any DataType plugin class as the 'type' value for an entry. paragraphs.paragraphs_type.*: type: config_entity label: 'Paragraphs type config' mapping: id: type: string label: 'ID' label: type: label label: 'Label'
  • 35. Typed Data Explorer Simple module to browse Typed Data. https://github.com/wellnet/typed_data_explorer
  • 37. Thanks for your attention!