SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
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!

Weitere ähnliche Inhalte

Was ist angesagt?

Uxpin Why Build a Design System
Uxpin Why Build a Design SystemUxpin Why Build a Design System
Uxpin Why Build a Design SystemLewis Lin 🦊
 
Evolving your Design System: People, Product, and Process
Evolving your Design System: People, Product, and ProcessEvolving your Design System: People, Product, and Process
Evolving your Design System: People, Product, and Processuxpin
 
7 tips to create visual presentations
7 tips to create visual presentations7 tips to create visual presentations
7 tips to create visual presentationsEmiland
 
Masters of SlideShare
Masters of SlideShareMasters of SlideShare
Masters of SlideShareKapost
 
Building a Design System: A Practitioner's Case Study
Building a Design System: A Practitioner's Case StudyBuilding a Design System: A Practitioner's Case Study
Building a Design System: A Practitioner's Case Studyuxpin
 
Design System as a Product
Design System as a ProductDesign System as a Product
Design System as a ProductThoughtworks
 
Building compelling business cases for Design Systems
Building compelling business cases for Design SystemsBuilding compelling business cases for Design Systems
Building compelling business cases for Design SystemsLaura Van Doore
 
Design Systems at Scale
Design Systems at ScaleDesign Systems at Scale
Design Systems at ScaleSarah Federman
 
Building a Mature Design System
Building a Mature Design SystemBuilding a Mature Design System
Building a Mature Design SystemDrew Burdick
 
So…What Do I Make? (Dan Mall)
So…What Do I Make? (Dan Mall)So…What Do I Make? (Dan Mall)
So…What Do I Make? (Dan Mall)Future Insights
 
How Game Developers Reach New Customers with Twitch
How Game Developers Reach New Customers with Twitch How Game Developers Reach New Customers with Twitch
How Game Developers Reach New Customers with Twitch Amazon Web Services
 
Design System: Dominando o Design at Scale
Design System: Dominando o Design at ScaleDesign System: Dominando o Design at Scale
Design System: Dominando o Design at ScaleGuilherme Gonzalez
 
Raw Fury: Pitch Deck Template
Raw Fury: Pitch Deck TemplateRaw Fury: Pitch Deck Template
Raw Fury: Pitch Deck TemplateJohan Toresson
 
Initiating and Sustaining Design Systems for the Enterprise
Initiating and Sustaining Design Systems for the EnterpriseInitiating and Sustaining Design Systems for the Enterprise
Initiating and Sustaining Design Systems for the Enterpriseuxpin
 
6 Ways to Quit Bullet Points with Style
6 Ways to Quit Bullet Points with Style6 Ways to Quit Bullet Points with Style
6 Ways to Quit Bullet Points with StylePodium Wisdom
 

Was ist angesagt? (20)

Uxpin Why Build a Design System
Uxpin Why Build a Design SystemUxpin Why Build a Design System
Uxpin Why Build a Design System
 
Evolving your Design System: People, Product, and Process
Evolving your Design System: People, Product, and ProcessEvolving your Design System: People, Product, and Process
Evolving your Design System: People, Product, and Process
 
7 tips to create visual presentations
7 tips to create visual presentations7 tips to create visual presentations
7 tips to create visual presentations
 
Design System 101
Design System 101Design System 101
Design System 101
 
Pitch framework
Pitch frameworkPitch framework
Pitch framework
 
Masters of SlideShare
Masters of SlideShareMasters of SlideShare
Masters of SlideShare
 
5 Ways To Surprise Your Audience (and keep their attention)
5 Ways To Surprise Your Audience (and keep their attention)5 Ways To Surprise Your Audience (and keep their attention)
5 Ways To Surprise Your Audience (and keep their attention)
 
Building a Design System: A Practitioner's Case Study
Building a Design System: A Practitioner's Case StudyBuilding a Design System: A Practitioner's Case Study
Building a Design System: A Practitioner's Case Study
 
Design System as a Product
Design System as a ProductDesign System as a Product
Design System as a Product
 
Building compelling business cases for Design Systems
Building compelling business cases for Design SystemsBuilding compelling business cases for Design Systems
Building compelling business cases for Design Systems
 
Design Systems at Scale
Design Systems at ScaleDesign Systems at Scale
Design Systems at Scale
 
Building a Mature Design System
Building a Mature Design SystemBuilding a Mature Design System
Building a Mature Design System
 
So…What Do I Make? (Dan Mall)
So…What Do I Make? (Dan Mall)So…What Do I Make? (Dan Mall)
So…What Do I Make? (Dan Mall)
 
How Game Developers Reach New Customers with Twitch
How Game Developers Reach New Customers with Twitch How Game Developers Reach New Customers with Twitch
How Game Developers Reach New Customers with Twitch
 
Design System: Dominando o Design at Scale
Design System: Dominando o Design at ScaleDesign System: Dominando o Design at Scale
Design System: Dominando o Design at Scale
 
Raw Fury: Pitch Deck Template
Raw Fury: Pitch Deck TemplateRaw Fury: Pitch Deck Template
Raw Fury: Pitch Deck Template
 
Initiating and Sustaining Design Systems for the Enterprise
Initiating and Sustaining Design Systems for the EnterpriseInitiating and Sustaining Design Systems for the Enterprise
Initiating and Sustaining Design Systems for the Enterprise
 
6 Ways to Quit Bullet Points with Style
6 Ways to Quit Bullet Points with Style6 Ways to Quit Bullet Points with Style
6 Ways to Quit Bullet Points with Style
 
Design System
Design SystemDesign System
Design System
 
Presentation Zen
Presentation ZenPresentation Zen
Presentation Zen
 

Ähnlich wie 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 RepresentationRandy Connolly
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7Zsolt 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 NotesLakshmiSarvani6
 
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] : DatastoreIMC Institute
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmersAlexander Varwijk
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5Mahmoud Ouf
 
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 DesignMarcusHeld1
 
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.pptxfacebookrecovery1
 
Graph db as metastore
Graph db as metastoreGraph db as metastore
Graph db as metastoreHaris 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 moduleJohan Gant
 
Lesson 2 data preprocessing
Lesson 2   data preprocessingLesson 2   data preprocessing
Lesson 2 data preprocessingAbdurRazzaqe1
 
Data Wrangling and Visualization Using Python
Data Wrangling and Visualization Using PythonData Wrangling and Visualization Using Python
Data Wrangling and Visualization Using PythonMOHITKUMAR1379
 
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 NewardJAX 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 @ LinkedInVitaly Gordon
 

Ähnlich wie 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
 

Kürzlich hochgeladen

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Kürzlich hochgeladen (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

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!