SlideShare a Scribd company logo
1 of 30
Download to read offline
Laravel Doctrine
A data-mapper approach
Hello!
Christian Nastasi
- Consultant
- Software Architect
- Technical Coach
- ~17 years developing stuff
- Nerd t-shirt lover
Eloquent
- Easy to read
- Easy to write
- Easy to learn
- Expressive
- SQL Injection safe
Eloquent is a powerful tool, but...
Problem:
// Data could be invalid
$user->email = ‘that’s not a valid email’;
$user->save();
Nothing prevents inconsistency
Bugs alert!
Problem:
- No property hinting on your IDE
- No static code analysis => No typo prevention
- Magic properties => Only manual refactor is possible
Error raised only at runtime!
Bugs alert!
$user->usermane = “christian.nastasi”;
$user->pasword = “that’s a secret”;
Problem:
- Violates SRP (Single Responsability Principle)
○ wraps a row in a database table or view
○ encapsulates the database access
○ adds domain logic on that data
● Test them is complex, really
○ It’s too close to the infrastructure, you can’t unit testing
your application without a real Database.
○ You have to drop, migrate and seeds for every single test.
That’s time expensive and complex to manage.
Eloquent is based on
Active Record Pattern
Active Record Pattern
“Active Record is a good choice for domain logic that isn’t
too complex, such as creates, reads, updates, and deletes.”
Martin Fowler
Then what if my domain logic
is complex?
What’s a Data Mapper?
The Data Mapper is a layer of software that separates the
in-memory objects from the database.
Its responsibility is to transfer data between the two and
also to isolate them from each other.
With Data Mapper the in-memory objects needn't know even
that there's a database present.
Martin Fowler
Doctrine
- 28.5 Milions of downloads
- Extended community
- 538 Contributors
- Inspired from Hibernate
Top italian contributors
#2 - Ocramius - 837 commits
(Marco Pivetta)
#12 - Jean85 - 28 commits
(Alessandro Lai)
Eloquent vs Doctrine
// Eloquent
$scientist = new Scientist();
$scientist->name = 'Albert';
$scientist->surname = 'Einstein';
$scientist->save();
$scientist->theories()->save(
Theory::create(['theory'=>'Theory of relativity'])
);
// Doctrine
$scientist = new Scientist(
'Albert',
'Einstein'
);
$scientist->addTheory(
new Theory('Theory of relativity')
);
EntityManager::persist($scientist);
EntityManager::flush();
Laravel Doctrine
253K ⇩ 425 ☆
Same concepts of Doctrine
- Entity
- EntityManager
- EntityRepository
Laravel + Doctrine: Set up
// Laravel 5.5
composer require "laravel-doctrine/orm:1.4.*"
Because of the auto package discovery feature Laravel 5.5
has, the ServiceProvider and Facades are automatically
registered.
php artisan vendor:publish --tag="config"
The DB configuration are inside the .env file, as usual
Cool and easy!
But how it works?
Our domain is a library
Let’s try with an example:
// Book
{
isbn: “0-553-29335-4”
title: “Foundation”
author: {
id: 42,
name: “Isaac”,
surname: “Asimov”
}
}
Data and Metadata // Entity
{
name: “Book”,
table: “books”,
properties: {
isbn: {
type: “string”,
max-length: 20
},
title: {
type: “string”,
max-length: 255
}
},
references: {
author: ”Author”
}
}
Metadata
Entities - Metadata
- By @Annotation
- By <XML> mapping file </XML>
- By YML
mapping
file
Entities - Model
namespace AppEntities;
use DoctrineORMMapping as ORM;
/**
* Class Book
*
* @package AppEntities
*
* @ORMEntity()
* @ORMTable("books")
*/
class Book
Entities - Fields
/**
* @ORMId
* @ORMColumn(type="string", length=20)
*/
private $isbn;
/**
* @ORMColumn(type="string", length=255)
*/
private $title; }
Entities - Relationships
/**
* @var Author
*
* @ManyToOne(targetEntity="Author")
* @JoinColumn(name="author_id", referencedColumnName="id")
*/
private $author;
Fetching type:
- EAGER
- LAZY (default)
- EXTRA_LAZY
Entities - Data accessing
public function __construct(string $isbn, string $title, Author $author)
{
$this->setIsbn($isbn); // Valid ISBN format
$this->setTitle($title); // Not empty
$this->author = $author; // Already validated
}
public function getIsbn(): string { … }
public function getTitle(): string { … }
public function getAuthor(): Author { … }
private function setIsbn(string $isbn): void { … }
private function setTitle(string $title) : void { … }
Schema generation
php artisan doctrine:info
php artisan doctrine:schema:validate
php artisan doctrine:schema:create
php artisan doctrine:schema:update
php artisan doctrine:schema:drop
// Facade
EntityManager::flush();
EntityManager::persist($entity);
$entity = EntityManager::find(Book::class, 1);
// Container
app('em');
app('DoctrineORMEntityManagerInterface');
// Dependency Injection
public function __construct (EntityManagerInterface $em)
Doctrine Entity Manager
$repository = EntityManager::getRepository(Book::class);
Doctrine Entity Repository: Generic
interface ObjectRepository
{
public function find($id): object;
public function findAll(): array;
public function findBy(array $criteria): array;
public function findOneBy(array $criteria): array;
public function getClassName(): string;
}
Doctrine Entity Repository
interface BookRepository
{
public function findByIsbn(string $isbn): Book;
public function findByTitle(string $title): array;
public function findByAuthor(Author $author): array;
}
Doctrine Entity Repository: Inheritance
use DoctrineORMEntityRepository;
class DoctrineBookRepository extends EntityRepository implements BookRepository
{
public function findByAuthor(Author $author): array
{
return $this->findBy(['author' => $author]);
}
/* … */
}
Doctrine Entity Repository: Composition
class DoctrineBookRepository implements BookRepository
{
private $repository;
public function __construct(ObjectRepository $repository)
{
$this->repository = $repository;
}
public function findByAuthor(Author $author): array
{
return $this->repository->findBy(['author' => $author]);
}
/* … */
}
Icing on the cake
- Authentication:
Integrated with Laravel Auth
- Extensions:
Gedmo & Berbelei. Provides extra power to your entities
- Migrations:
Create migrations from models metadatas
- ACL:
Access Control out of the box
- Fluent:
Define the models metadatas using a fluent sintax
- Scout:
Add full-text search into your Doctrine entities
Thanks! Questions?
Contatti:
- christian.nastasi@gmail.com
- https://github.com/cnastasi
- @c_nastasi
https://joind.in/talk/37eaf

More Related Content

What's hot

What is the difference between a good and a bad repository? (Forum PHP 2018)
What is the difference between a good and a bad repository? (Forum PHP 2018)What is the difference between a good and a bad repository? (Forum PHP 2018)
What is the difference between a good and a bad repository? (Forum PHP 2018)Arnaud Langlade
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mockingKonstantin Kudryashov
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Rafael Dohms
 
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPositive Hack Days
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Mail.ru Group
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective CNeha Gupta
 
Pro bun-fighting - Working with JavaScript projects
Pro bun-fighting - Working with JavaScript projectsPro bun-fighting - Working with JavaScript projects
Pro bun-fighting - Working with JavaScript projectsFrances Berriman
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code ReviewDamien Seguy
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erickokelloerick
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
 
Indexing documents
Indexing documentsIndexing documents
Indexing documentsMongoDB
 

What's hot (19)

Current state-of-php
Current state-of-phpCurrent state-of-php
Current state-of-php
 
What is the difference between a good and a bad repository? (Forum PHP 2018)
What is the difference between a good and a bad repository? (Forum PHP 2018)What is the difference between a good and a bad repository? (Forum PHP 2018)
What is the difference between a good and a bad repository? (Forum PHP 2018)
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18Writing code you won’t hate tomorrow - PHPCE18
Writing code you won’t hate tomorrow - PHPCE18
 
Closer look at PHP Unserialization by Ashwin Shenoi
Closer look at PHP Unserialization by Ashwin ShenoiCloser look at PHP Unserialization by Ashwin Shenoi
Closer look at PHP Unserialization by Ashwin Shenoi
 
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an Analysis
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Memory management in Objective C
Memory management in Objective CMemory management in Objective C
Memory management in Objective C
 
Sequelize
SequelizeSequelize
Sequelize
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Pro bun-fighting - Working with JavaScript projects
Pro bun-fighting - Working with JavaScript projectsPro bun-fighting - Working with JavaScript projects
Pro bun-fighting - Working with JavaScript projects
 
PHP Static Code Review
PHP Static Code ReviewPHP Static Code Review
PHP Static Code Review
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Java New Features
Java New FeaturesJava New Features
Java New Features
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
Objective C Memory Management
Objective C Memory ManagementObjective C Memory Management
Objective C Memory Management
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Indexing documents
Indexing documentsIndexing documents
Indexing documents
 

Similar to Laravel doctrine

Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingTricode (part of Dept)
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
Architecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented designArchitecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented designJean Michel
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3Nate Abele
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionNate Abele
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
Drupal 8: Entities
Drupal 8: EntitiesDrupal 8: Entities
Drupal 8: Entitiesdrubb
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...andrewnacin
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 

Similar to Laravel doctrine (20)

Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
Architecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented designArchitecture logicielle #3 : object oriented design
Architecture logicielle #3 : object oriented design
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Perl object ?
Perl object ?Perl object ?
Perl object ?
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Fatc
FatcFatc
Fatc
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Drupal 8: Entities
Drupal 8: EntitiesDrupal 8: Entities
Drupal 8: Entities
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 

Recently uploaded

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
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
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
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
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
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
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Recently uploaded (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
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
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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 ...
 
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
 
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
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.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
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
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 🔝✔️✔️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

Laravel doctrine

  • 2. Hello! Christian Nastasi - Consultant - Software Architect - Technical Coach - ~17 years developing stuff - Nerd t-shirt lover
  • 3. Eloquent - Easy to read - Easy to write - Easy to learn - Expressive - SQL Injection safe
  • 4. Eloquent is a powerful tool, but...
  • 5. Problem: // Data could be invalid $user->email = ‘that’s not a valid email’; $user->save(); Nothing prevents inconsistency Bugs alert!
  • 6. Problem: - No property hinting on your IDE - No static code analysis => No typo prevention - Magic properties => Only manual refactor is possible Error raised only at runtime! Bugs alert! $user->usermane = “christian.nastasi”; $user->pasword = “that’s a secret”;
  • 7. Problem: - Violates SRP (Single Responsability Principle) ○ wraps a row in a database table or view ○ encapsulates the database access ○ adds domain logic on that data ● Test them is complex, really ○ It’s too close to the infrastructure, you can’t unit testing your application without a real Database. ○ You have to drop, migrate and seeds for every single test. That’s time expensive and complex to manage.
  • 8. Eloquent is based on Active Record Pattern
  • 9. Active Record Pattern “Active Record is a good choice for domain logic that isn’t too complex, such as creates, reads, updates, and deletes.” Martin Fowler
  • 10. Then what if my domain logic is complex?
  • 11. What’s a Data Mapper? The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn't know even that there's a database present. Martin Fowler
  • 12. Doctrine - 28.5 Milions of downloads - Extended community - 538 Contributors - Inspired from Hibernate Top italian contributors #2 - Ocramius - 837 commits (Marco Pivetta) #12 - Jean85 - 28 commits (Alessandro Lai)
  • 13. Eloquent vs Doctrine // Eloquent $scientist = new Scientist(); $scientist->name = 'Albert'; $scientist->surname = 'Einstein'; $scientist->save(); $scientist->theories()->save( Theory::create(['theory'=>'Theory of relativity']) ); // Doctrine $scientist = new Scientist( 'Albert', 'Einstein' ); $scientist->addTheory( new Theory('Theory of relativity') ); EntityManager::persist($scientist); EntityManager::flush();
  • 14. Laravel Doctrine 253K ⇩ 425 ☆ Same concepts of Doctrine - Entity - EntityManager - EntityRepository
  • 15. Laravel + Doctrine: Set up // Laravel 5.5 composer require "laravel-doctrine/orm:1.4.*" Because of the auto package discovery feature Laravel 5.5 has, the ServiceProvider and Facades are automatically registered. php artisan vendor:publish --tag="config" The DB configuration are inside the .env file, as usual
  • 16. Cool and easy! But how it works? Our domain is a library Let’s try with an example:
  • 17. // Book { isbn: “0-553-29335-4” title: “Foundation” author: { id: 42, name: “Isaac”, surname: “Asimov” } } Data and Metadata // Entity { name: “Book”, table: “books”, properties: { isbn: { type: “string”, max-length: 20 }, title: { type: “string”, max-length: 255 } }, references: { author: ”Author” } } Metadata
  • 18. Entities - Metadata - By @Annotation - By <XML> mapping file </XML> - By YML mapping file
  • 19. Entities - Model namespace AppEntities; use DoctrineORMMapping as ORM; /** * Class Book * * @package AppEntities * * @ORMEntity() * @ORMTable("books") */ class Book
  • 20. Entities - Fields /** * @ORMId * @ORMColumn(type="string", length=20) */ private $isbn; /** * @ORMColumn(type="string", length=255) */ private $title; }
  • 21. Entities - Relationships /** * @var Author * * @ManyToOne(targetEntity="Author") * @JoinColumn(name="author_id", referencedColumnName="id") */ private $author; Fetching type: - EAGER - LAZY (default) - EXTRA_LAZY
  • 22. Entities - Data accessing public function __construct(string $isbn, string $title, Author $author) { $this->setIsbn($isbn); // Valid ISBN format $this->setTitle($title); // Not empty $this->author = $author; // Already validated } public function getIsbn(): string { … } public function getTitle(): string { … } public function getAuthor(): Author { … } private function setIsbn(string $isbn): void { … } private function setTitle(string $title) : void { … }
  • 23. Schema generation php artisan doctrine:info php artisan doctrine:schema:validate php artisan doctrine:schema:create php artisan doctrine:schema:update php artisan doctrine:schema:drop
  • 24. // Facade EntityManager::flush(); EntityManager::persist($entity); $entity = EntityManager::find(Book::class, 1); // Container app('em'); app('DoctrineORMEntityManagerInterface'); // Dependency Injection public function __construct (EntityManagerInterface $em) Doctrine Entity Manager
  • 25. $repository = EntityManager::getRepository(Book::class); Doctrine Entity Repository: Generic interface ObjectRepository { public function find($id): object; public function findAll(): array; public function findBy(array $criteria): array; public function findOneBy(array $criteria): array; public function getClassName(): string; }
  • 26. Doctrine Entity Repository interface BookRepository { public function findByIsbn(string $isbn): Book; public function findByTitle(string $title): array; public function findByAuthor(Author $author): array; }
  • 27. Doctrine Entity Repository: Inheritance use DoctrineORMEntityRepository; class DoctrineBookRepository extends EntityRepository implements BookRepository { public function findByAuthor(Author $author): array { return $this->findBy(['author' => $author]); } /* … */ }
  • 28. Doctrine Entity Repository: Composition class DoctrineBookRepository implements BookRepository { private $repository; public function __construct(ObjectRepository $repository) { $this->repository = $repository; } public function findByAuthor(Author $author): array { return $this->repository->findBy(['author' => $author]); } /* … */ }
  • 29. Icing on the cake - Authentication: Integrated with Laravel Auth - Extensions: Gedmo & Berbelei. Provides extra power to your entities - Migrations: Create migrations from models metadatas - ACL: Access Control out of the box - Fluent: Define the models metadatas using a fluent sintax - Scout: Add full-text search into your Doctrine entities
  • 30. Thanks! Questions? Contatti: - christian.nastasi@gmail.com - https://github.com/cnastasi - @c_nastasi https://joind.in/talk/37eaf