SlideShare a Scribd company logo
1 of 48
Download to read offline
Save repository
from save
Norbert Orzechowicz

@norzechowicz
Repository
Here I should add some complicated
description of repository pattern. 

But instead of that…
Keep calm
and
think about…
bookshelf
Bookshelf specification
• it contains books
• it contains books from mixed categories
• it allows you to add new books when it’s not full
• it allows you to find and pick a book or books
• it allows you to remove specific book or books from it
Bookshelf specification
• it contains books
• it contains books from mixed categories
• it allows you to add new books when it’s not full
• it allows you to find and pick specific books/book
• it allows you to remove specific books/book from it
<?php
interface Bookshelf
{
/**
* @param Book $book
* @return bool
*/
public function contains(Book $book);
/**
* @param Book $book
*/
public function add(Book $book);
/**
* @param Title $title
* @return Book
*/
public function findBy(Title $title);
/**
* @param Book $book
*/
public function remove(Book $book);
}
Conclusions
• bookshelf acts as a collection
• bookshelf does not handle book changes
• bookshelf implements repository pattern
Repository
Mediates between the domain and data
mapping layers using a collection-like
interface for accessing domain objects.
Martin Fowler
From pure data
to entity
Database
+----+-------------------+------------+----------------------------------+
| id | title | author | description |
+----+-------------------+------------+----------------------------------+
| 1 | 50 shades of grey | E.L. James | Fifty Shades of Grey is a... |
+----+-------------------+------------+----------------------------------+
But first let me introduce
you few building blocks
Data Access Object
<?php
class BookDataAccessObject
{
public function getByTitle($title);



public function saveNew(array $data);
}
Hydrator
<?php
class BookHydrator
{
/**
* @param array $data
* @return Book
*/
public function hydrateBook($data = []);
}
Converter
<?php
class BookConverter
{
/**
* @param Book $book
* @return array
*/
public function toArray(Book $book);
}
Do you already know
where to assemble them?
Book Repository
<?php
class Bookshelf
{
/**
* @param Title $title
* @return Book
*/
public function findBy(Title $title)
{
$bookData = $this->dao->getByTitle((string) $title);
$book = $this->hydrator->hydrateBook($bookData);
return $book;
}
}
Book Repository
<?php
class Bookshelf
{
/**
* @param Book $book
*/
public function add(Book $book)
{
$data = $this->converter->toArray($book);
$this->dao->saveNew($data);
}
}
What about changes?
Well if you don’t ask your bookshelf
to handle changes why would you
like to ask repository for that?
Example of repository with
too many responsibilities
<?php
interface Bookshelf
{
public function contains(Book $book);
public function add(Book $book);
public function findBy(Title $title);
public function remove(Book $book);
/**
* Sometimes also Update/Handle/Persist
* @param Book $book
*/
public function save(Book $book);
}
Persistence
repositories?
Excuses…
So how to handle
changes?
Unit of Work
Maintains a list of objects affected by
a business transaction and coordinates
the writing out of changes and the resolution
of concurrency problems.
Martin Fowler
Unit of Work
<?php
class UnitOfWork
{
public function watch($entity);
public function remove($entity);
public function commit();
public function rollback();
}
UoW expected extension
points
• Entity Created
• Entity Updated
• Entity Removed
Repository & UoW
<?php
class BookRepository
{
public function add(Book $book)
{
$this->uow->watch($book);
}
public function findBy(Title $title)
{
$bookData = $this->dao->getByTitle((string) $title);
$book = $this->hydrator->hydrateBook($bookData);
$this->uow->watch($book);
return $book;
}
}
Commit?
(save changes, create new entities, delete entities)
Dummy Update Example
<?php
class BookController
{
public function updateBookDescriptionAction(Request $request, $title)
{
$book = $this->get('book.repository')->findBy(new Title($title));
$form = $this->createForm(new FormType());
$form->handle($request);
if ($form->isValid()) {
$book->updateDescription($form->get('description')->getData());
$this->get('unit_of_work')->commit();
return $this->redirect($this->generateUrl('homepage');
}
return $this->render('book/updateDescription.html.twig', [
'book' => $book, 'form' => $form->createView()
]);
}
}
Dummy Remove Example
<?php
class BookController
{
public function removeBookAction($title)
{
$book = $this->get('book.repository')->remove(new Title($title));
$this->get('unit_of_work')->commit();
return $this->render('book/updateDescription.html.twig', [
'book' => $book, 'form' => $form->createView()
]);
}
}
Rollback?
In most web applications there
is no need for rollback because
objects become useless when
response is created.
Still wanna see more?
(more of abstraction of course)
https://github.com/isolate-org
Isolate is a PHP framework that will help you in isolating
business logic from persistence layer.
current version: 1.0.0-alpha2
https://twitter.com/isolate_php
Isolate
Think about it as a registry of persistence contexts
Persistence Context
It’s responsible for opening and closing transactions
Transaction
It’s an abstraction over the unit of work (more or less)
Repository with Isolate
<?php
class BookRepository
{
public function add(Book $book)
{
$persistenceContext = $this->get('isolate')->getContext();
$transaction = $persistenceContext->openTransaction();
$transaction->persist($book);
}
public function findBy(Title $title)
{
$bookData = $this->dao->getByTitle((string) $title);
$book = $this->hydrator->hydrateBook($bookData);
$persistenceContext = $this->get('isolate')->getContext();
if ($persistenceContext->hasOpenTransaction()) {
$transaction = $persistenceContext->openTransaction();
$transaction->persist($book);
}
return $book;
}
}
Update action example
<?php
class BookController
{
public function updateBookDescriptionAction(Request $request, $title)
{
$this->get('isolate')->getContext()->openTransaction();
$book = $this->get('book.repository')->findBy(new Title($title));
$form = $this->createForm(new FormType());
$form->handle($request);
if ($form->isValid()) {
$book->updateDescription($form->get('description')->getData());
$this->get('isolate')->getContext()->closeTransaction();
return $this->redirect($this->generateUrl('homepage');
}
return $this->render('book/updateDescription.html.twig', [
'book' => $book, 'form' => $form->createView()
]);
}
}
But there is more code
in this example….
Refactoring
• implement commands and command handlers
(tactician)
• implement middlewares (tactician)
• move isolate transaction management to
middlewares
• move business logic into command handlers
Transaction middleware
<?php
/**
* This code is available in Isolate Tactician Bridge
*/
class TransactionMiddleware implements Middleware
{
public function execute($command, callable $next)
{
$context = $this->isolate->getContext();
$transaction = $context->openTransaction();
try {
$returnValue = $next($command);
$context->closeTransaction();
return $returnValue;
} catch (Exception $e) {
$transaction->rollback();
throw $e;
}
}
}
Update book command
handler
<?php
class UpdateBookHandler
{
public function handle(UpdateBookCommand $command)
{
$book = $this->bookshelf->findBy(new Title($command->getTitle()));
if (empty($book)) {
throw new BookNotFoundException();
}
$book->updateDescription($command->getDescription());
}
}
Update book controller
<?php
class BookController
{
public function updateBookAction(Request $request, $title)
{
$form = $this->createForm(new FormType());
$form->handle($request);
if ($form->isValid()) {
$command = new UpdateBookCommand($title, $form->get('description')->getData());
$this->get('command_bus')->handle($command);
return $this->redirect($this->generateUrl('homepage');
}
return $this->render('book/updateDescription.html.twig', [
'book' => $book, 'form' => $form->createView()
]);
}
}
Isolate extensions
• Tactician Bridge

https://github.com/isolate-org/tactician-bridge
• Doctrine Bridge

https://github.com/isolate-org/doctrine-bridge
• Symfony Bundle

https://github.com/isolate-org/symfony-bundle



Advantages
• application totally decoupled from storage
• possibility to switch storage for tests
• possibility to replace ORM with ODM, webservice,
filesystem or anything else
• possibility to delay a decision about storage type
• possibility to increase performance by replacing auto-
generated sql queries with custom, optimized queries
• clean architecture not impacted by persistence layer
Disadvantages
• higher entry point for junior developers
• require better understanding of how your storage
works
Questions?

More Related Content

Viewers also liked

MVVM в WinForms – DevExpress Way (теория и практика)
MVVM в WinForms – DevExpress Way (теория и практика)MVVM в WinForms – DevExpress Way (теория и практика)
MVVM в WinForms – DevExpress Way (теория и практика)GoSharp
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkMd. Mahedee Hasan
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
Repository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir PoudelRepository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir PoudelSameer Poudel
 
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
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsHatim Hakeel
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In DepthKirk Bushell
 

Viewers also liked (10)

MVVM в WinForms – DevExpress Way (теория и практика)
MVVM в WinForms – DevExpress Way (теория и практика)MVVM в WinForms – DevExpress Way (теория и практика)
MVVM в WinForms – DevExpress Way (теория и практика)
 
Generic repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity FrameworkGeneric repository pattern with ASP.NET MVC and Entity Framework
Generic repository pattern with ASP.NET MVC and Entity Framework
 
Solid vs php
Solid vs phpSolid vs php
Solid vs php
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Repository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir PoudelRepository design pattern in laravel - Samir Poudel
Repository design pattern in laravel - Samir Poudel
 
DDD Repository
DDD RepositoryDDD Repository
DDD Repository
 
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
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design Patterns
 
PhpSpec extension points
PhpSpec extension pointsPhpSpec extension points
PhpSpec extension points
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
 

Similar to Save Repository From Save

SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
X Query for beginner
X Query for beginnerX Query for beginner
X Query for beginnerNguyen Quang
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-entechbed
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...Corley S.r.l.
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...Walter Dal Mut
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3Nate Abele
 
Development Approach
Development ApproachDevelopment Approach
Development Approachalexkingorg
 
Firebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesFirebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesPeter Friese
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbaivibrantuser
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objectsjulien pauli
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aidawaraiotoko
 
Driving Design with PhpSpec
Driving Design with PhpSpecDriving Design with PhpSpec
Driving Design with PhpSpecCiaranMcNulty
 
Arquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackArquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackNelson Glauber Leal
 

Similar to Save Repository From Save (20)

SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
X Query for beginner
X Query for beginnerX Query for beginner
X Query for beginner
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
First java-server-faces-tutorial-en
First java-server-faces-tutorial-enFirst java-server-faces-tutorial-en
First java-server-faces-tutorial-en
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
A single language for backend and frontend from AngularJS to cloud with Clau...
A single language for backend and frontend  from AngularJS to cloud with Clau...A single language for backend and frontend  from AngularJS to cloud with Clau...
A single language for backend and frontend from AngularJS to cloud with Clau...
 
Xpath & xquery
Xpath & xqueryXpath & xquery
Xpath & xquery
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Development Approach
Development ApproachDevelopment Approach
Development Approach
 
Firebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroesFirebase for Apple Developers - SwiftHeroes
Firebase for Apple Developers - SwiftHeroes
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
OOPs Concept
OOPs ConceptOOPs Concept
OOPs Concept
 
Php course-in-navimumbai
Php course-in-navimumbaiPhp course-in-navimumbai
Php course-in-navimumbai
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objects
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
SPL Primer
SPL PrimerSPL Primer
SPL Primer
 
Driving Design with PhpSpec
Driving Design with PhpSpecDriving Design with PhpSpec
Driving Design with PhpSpec
 
laravel-53
laravel-53laravel-53
laravel-53
 
Arquitetando seu app Android com Jetpack
Arquitetando seu app Android com JetpackArquitetando seu app Android com Jetpack
Arquitetando seu app Android com Jetpack
 
Modern php
Modern phpModern php
Modern php
 

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
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
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
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
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
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
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
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
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
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
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
 
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
 

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
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .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
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
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
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
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...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
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
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
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
 
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 🔝✔️✔️
 

Save Repository From Save

  • 3. Repository Here I should add some complicated description of repository pattern. 
 But instead of that…
  • 5. Bookshelf specification • it contains books • it contains books from mixed categories • it allows you to add new books when it’s not full • it allows you to find and pick a book or books • it allows you to remove specific book or books from it
  • 6. Bookshelf specification • it contains books • it contains books from mixed categories • it allows you to add new books when it’s not full • it allows you to find and pick specific books/book • it allows you to remove specific books/book from it
  • 7. <?php interface Bookshelf { /** * @param Book $book * @return bool */ public function contains(Book $book); /** * @param Book $book */ public function add(Book $book); /** * @param Title $title * @return Book */ public function findBy(Title $title); /** * @param Book $book */ public function remove(Book $book); }
  • 8. Conclusions • bookshelf acts as a collection • bookshelf does not handle book changes • bookshelf implements repository pattern
  • 9. Repository Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects. Martin Fowler
  • 11. Database +----+-------------------+------------+----------------------------------+ | id | title | author | description | +----+-------------------+------------+----------------------------------+ | 1 | 50 shades of grey | E.L. James | Fifty Shades of Grey is a... | +----+-------------------+------------+----------------------------------+
  • 12. But first let me introduce you few building blocks
  • 13. Data Access Object <?php class BookDataAccessObject { public function getByTitle($title);
 
 public function saveNew(array $data); }
  • 14. Hydrator <?php class BookHydrator { /** * @param array $data * @return Book */ public function hydrateBook($data = []); }
  • 15. Converter <?php class BookConverter { /** * @param Book $book * @return array */ public function toArray(Book $book); }
  • 16. Do you already know where to assemble them?
  • 17. Book Repository <?php class Bookshelf { /** * @param Title $title * @return Book */ public function findBy(Title $title) { $bookData = $this->dao->getByTitle((string) $title); $book = $this->hydrator->hydrateBook($bookData); return $book; } }
  • 18. Book Repository <?php class Bookshelf { /** * @param Book $book */ public function add(Book $book) { $data = $this->converter->toArray($book); $this->dao->saveNew($data); } }
  • 20. Well if you don’t ask your bookshelf to handle changes why would you like to ask repository for that?
  • 21. Example of repository with too many responsibilities <?php interface Bookshelf { public function contains(Book $book); public function add(Book $book); public function findBy(Title $title); public function remove(Book $book); /** * Sometimes also Update/Handle/Persist * @param Book $book */ public function save(Book $book); }
  • 23. So how to handle changes?
  • 24. Unit of Work Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. Martin Fowler
  • 25. Unit of Work <?php class UnitOfWork { public function watch($entity); public function remove($entity); public function commit(); public function rollback(); }
  • 26. UoW expected extension points • Entity Created • Entity Updated • Entity Removed
  • 27. Repository & UoW <?php class BookRepository { public function add(Book $book) { $this->uow->watch($book); } public function findBy(Title $title) { $bookData = $this->dao->getByTitle((string) $title); $book = $this->hydrator->hydrateBook($bookData); $this->uow->watch($book); return $book; } }
  • 28. Commit? (save changes, create new entities, delete entities)
  • 29. Dummy Update Example <?php class BookController { public function updateBookDescriptionAction(Request $request, $title) { $book = $this->get('book.repository')->findBy(new Title($title)); $form = $this->createForm(new FormType()); $form->handle($request); if ($form->isValid()) { $book->updateDescription($form->get('description')->getData()); $this->get('unit_of_work')->commit(); return $this->redirect($this->generateUrl('homepage'); } return $this->render('book/updateDescription.html.twig', [ 'book' => $book, 'form' => $form->createView() ]); } }
  • 30. Dummy Remove Example <?php class BookController { public function removeBookAction($title) { $book = $this->get('book.repository')->remove(new Title($title)); $this->get('unit_of_work')->commit(); return $this->render('book/updateDescription.html.twig', [ 'book' => $book, 'form' => $form->createView() ]); } }
  • 32. In most web applications there is no need for rollback because objects become useless when response is created.
  • 33. Still wanna see more? (more of abstraction of course)
  • 34. https://github.com/isolate-org Isolate is a PHP framework that will help you in isolating business logic from persistence layer. current version: 1.0.0-alpha2 https://twitter.com/isolate_php
  • 35. Isolate Think about it as a registry of persistence contexts
  • 36. Persistence Context It’s responsible for opening and closing transactions
  • 37. Transaction It’s an abstraction over the unit of work (more or less)
  • 38. Repository with Isolate <?php class BookRepository { public function add(Book $book) { $persistenceContext = $this->get('isolate')->getContext(); $transaction = $persistenceContext->openTransaction(); $transaction->persist($book); } public function findBy(Title $title) { $bookData = $this->dao->getByTitle((string) $title); $book = $this->hydrator->hydrateBook($bookData); $persistenceContext = $this->get('isolate')->getContext(); if ($persistenceContext->hasOpenTransaction()) { $transaction = $persistenceContext->openTransaction(); $transaction->persist($book); } return $book; } }
  • 39. Update action example <?php class BookController { public function updateBookDescriptionAction(Request $request, $title) { $this->get('isolate')->getContext()->openTransaction(); $book = $this->get('book.repository')->findBy(new Title($title)); $form = $this->createForm(new FormType()); $form->handle($request); if ($form->isValid()) { $book->updateDescription($form->get('description')->getData()); $this->get('isolate')->getContext()->closeTransaction(); return $this->redirect($this->generateUrl('homepage'); } return $this->render('book/updateDescription.html.twig', [ 'book' => $book, 'form' => $form->createView() ]); } }
  • 40. But there is more code in this example….
  • 41. Refactoring • implement commands and command handlers (tactician) • implement middlewares (tactician) • move isolate transaction management to middlewares • move business logic into command handlers
  • 42. Transaction middleware <?php /** * This code is available in Isolate Tactician Bridge */ class TransactionMiddleware implements Middleware { public function execute($command, callable $next) { $context = $this->isolate->getContext(); $transaction = $context->openTransaction(); try { $returnValue = $next($command); $context->closeTransaction(); return $returnValue; } catch (Exception $e) { $transaction->rollback(); throw $e; } } }
  • 43. Update book command handler <?php class UpdateBookHandler { public function handle(UpdateBookCommand $command) { $book = $this->bookshelf->findBy(new Title($command->getTitle())); if (empty($book)) { throw new BookNotFoundException(); } $book->updateDescription($command->getDescription()); } }
  • 44. Update book controller <?php class BookController { public function updateBookAction(Request $request, $title) { $form = $this->createForm(new FormType()); $form->handle($request); if ($form->isValid()) { $command = new UpdateBookCommand($title, $form->get('description')->getData()); $this->get('command_bus')->handle($command); return $this->redirect($this->generateUrl('homepage'); } return $this->render('book/updateDescription.html.twig', [ 'book' => $book, 'form' => $form->createView() ]); } }
  • 45. Isolate extensions • Tactician Bridge
 https://github.com/isolate-org/tactician-bridge • Doctrine Bridge
 https://github.com/isolate-org/doctrine-bridge • Symfony Bundle
 https://github.com/isolate-org/symfony-bundle
 

  • 46. Advantages • application totally decoupled from storage • possibility to switch storage for tests • possibility to replace ORM with ODM, webservice, filesystem or anything else • possibility to delay a decision about storage type • possibility to increase performance by replacing auto- generated sql queries with custom, optimized queries • clean architecture not impacted by persistence layer
  • 47. Disadvantages • higher entry point for junior developers • require better understanding of how your storage works