SlideShare a Scribd company logo
Programista PHP, Magento Developer
Aurora Creation sp. z o.o.
Łukasz Paliwoda
luk.paliwoda@gmail.com
l.paliwoda@auroracreation.com
S O L I D
“On the one hand, if the bricks aren’t well made, the architecture of the building
doesn’t matter much. On the other hand, you can make a substantial mess with
well-made bricks.”
Robert C. Martin
SOLID
SOLID is a acronym for five design principles intended to make software
designs more understandable, flexible and maintainable.
● Zebrane przez Robert C. Martin
● Nazwane przez Michael Feathers w 2004
S R P
O C P
L S P
I S P
D I P
Single Responsibility Principle
Open/Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
S O L I D
SOLID
Single Responsibility Principle
“A class should only have a single responsibility, that is, only changes to one
part of the software's specification should be able to affect the specification of
the class.”
SOLID
SOLID
class Menu
{
public function getMenu()
{
$url = 'http://example.com/menu.xml';
$string = $this->download($url);
$response = $this->parse($string);
return $response;
}
private function parse($string) { /* some logic */ }
private function download($url) { /* some logic */ }
private function log($message) { /* some logic */ }
}
$menuDownloader = new Menu();
$menu = $menu->getMenu();
SOLID
class Menu
{
private $menuParser;
private $contentProvider;
public function __construct(
XmlParser $menuParser,
HttpClient $contentProvider
) {
$this->menuParser = $menuParser;
$this->contentProvider = $contentProvider;
}
public function getMenu()
{
$rawContent = $this->contentProvider->getRawContent();
$parsedMenu = $this->parser->parse($rawContent);
return $parsedMenu;
}
}
$parser = new XmlParser();
$httpClient = new HttpClient();
$menu = new Menu($parser, $httpClient);
try {
$menu = $menu->getMenu();
} catch (Exception $e) {
echo $e->getMessage();
}
S O L I D
SOLID
Open/Closed Principle
"Software entities ... should be open for extension, but closed for
modification."
SOLID
SOLID
class Publisher
{
public function display($type)
{
switch($type) {
case 'screen':
/* some logic */
break;
case 'rss':
/* some logic */
break;
}
}
}
$publsher = new Publisher();
$publsher->display('screen');
$publsher->display('rss');
SOLID
interface PublisherInterface
{
public function getContent();
}
class Publisher
{
public function display(PublisherInterface $publisher)
{
$publisher->getContent();
}
}
class ScreenPublisher implements PublisherInterface
{
public function getContent() { /* some logic */ }
}
class RssPublisher implements PublisherInterface
{
public function getContent() { /* some logic */ }
}
SOLID
$publsher = new Publisher();
$screenPublisher = new ScreenPublisher();
$publsher->display($screenPublisher);
$rssPublisher = new RssPublisher();
$publsher->display($rssPublisher);
class PrintPublisher implements PublisherInterface
{
public function getContent() { /* some logic */ }
}
$printPublisher = new PrintPublisher();
$publsher->display($printPublisher);
S O L I D
SOLID
Liskov Substitution Principle
"Objects in a program should be replaceable with instances of their subtypes
without altering the correctness of that program."
SOLID
SOLID
class Ptak
{
public function lec() { /* some logic */ }
}
class Golab extends Ptak
{
}
class Strus extends Ptak
{
public function lec()
{
throw new Exception('Not Implemented');
}
}
class Ptak
{
}
class LatajacyPtak extends Ptak
{
public function lec() { /* some logic */ }
}
public class Golab extends LatajacyPtak
{
}
public class Strus extends Ptak
{
}
SOLID
interface Jednoslad
{
public function jedz();
}
class Rower implements Jednoslad
{
public function jedz();
}
$notebook = new Rower();
$notebook->jedz();
class Motor implements Jednoslad
{
public function wlacz()
{
/* some logic */
}
public function jedz()
{
/* some logic */
}
}
$tablet = new Motor();
$tablet->jedz();
// throw new Exception("You need to start the engine")
S O L I D
SOLID
Interface Segregation Principle
"Many client-specific interfaces are better than one general-purpose
interface."
SOLID
SOLID
interface FormatterInterface
{
public function toPDF($content);
public function toXML($content);
public function toJSON($content);
}
class Formatter implements FormatterInterface
{
public function toPDF($content)
{
throw new Exception('Not Implemented');
}
public function toXML($content)
{
/* some logic */
}
public function toJSON($content)
{
/* some logic */
}
}
SOLID
interface PdfFormatterInterface
{
public function toPDF($content);
}
interface XmlFormatterInterface
{
public function toXML($content);
}
interface JsonFormatterInterface
{
public function toJSON($content);
}
class Formatter implements JsonFormatterInterface, XmlFormatterInterface
{
public function toJSON($content)
{
/* some logic */
}
public function toXML($content)
{
/* some logic */
}
}
S O L I D
SOLID
Dependency Inversion Principle
“Entities must depend on abstractions not on concretions.”
SOLID
SOLID
SOLID
class MysqlConnection
{
public function connect()
{
/* some logic */
}
}
class PasswordReminder
{
private $connection;
public function __construct(MysqlConnection $connection)
{
$this->connection = $connection;
}
}
SOLID
interface DbConnectionInterface
{
public function connect();
}
class MysqlConnection implements DbConnectionInterface
{
public function connect()
{
/* some logic */
}
}
class PasswordReminder
{
private $connection;
public function __construct(DbConnectionInterface $connection)
{
$this->connection = $connection;
}
}
Podsumowanie
● klasa powinna mieć jeden i tylko jeden powód do zmiany
● pozwól na zmianę zachowania systemu poprzez dodawanie nowego kodu,
a nie modyfikowanie istniejącego
● buduj elementy tak aby były wzajemnie wymienne
● unikaj tworzenia zależności od elementów których nie potrzebujesz
● uniezależnij od siebie kod implementujący poszczególne warstwy
DZIĘKUJĘ

More Related Content

What's hot

international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
XSolve
 
What's new with PHP7
What's new with PHP7What's new with PHP7
What's new with PHP7
SWIFTotter Solutions
 
안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩
GDG Korea
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
Marco Vito Moscaritolo
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Fabien Potencier
 
Introduction to DI(C)
Introduction to DI(C)Introduction to DI(C)
Introduction to DI(C)
Radek Benkel
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
Kacper Gunia
 
Rich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 ApplicationRich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 Application
Kirill Chebunin
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
Kacper Gunia
 
Zend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency InjectionZend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency Injection
Abdul Malik Ikhsan
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
Alexander Varwijk
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2Hugo Hamon
 
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
Leonardo Proietti
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash Course
Colin O'Dell
 
TDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for BusinessTDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for Business
tdc-globalcode
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
Denis Ristic
 
Developing for Business
Developing for BusinessDeveloping for Business
Developing for Business
Antonio Spinelli
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 

What's hot (20)

international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
What's new with PHP7
What's new with PHP7What's new with PHP7
What's new with PHP7
 
안드로이드 데이터 바인딩
안드로이드 데이터 바인딩안드로이드 데이터 바인딩
안드로이드 데이터 바인딩
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
Introduction to DI(C)
Introduction to DI(C)Introduction to DI(C)
Introduction to DI(C)
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
Rich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 ApplicationRich Model And Layered Architecture in SF2 Application
Rich Model And Layered Architecture in SF2 Application
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Zend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency InjectionZend Framework 2 : Dependency Injection
Zend Framework 2 : Dependency Injection
 
Multilingualism makes better programmers
Multilingualism makes better programmersMultilingualism makes better programmers
Multilingualism makes better programmers
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
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
 
PHP 7 Crash Course
PHP 7 Crash CoursePHP 7 Crash Course
PHP 7 Crash Course
 
TDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for BusinessTDC2016SP - Trilha Developing for Business
TDC2016SP - Trilha Developing for Business
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
Developing for Business
Developing for BusinessDeveloping for Business
Developing for Business
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Twitter codeigniter library
Twitter codeigniter libraryTwitter codeigniter library
Twitter codeigniter library
 

Similar to SOLID

Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Krzysztof Menżyk
 
S.O.L.I.D. Principles
S.O.L.I.D. PrinciplesS.O.L.I.D. Principles
S.O.L.I.D. Principles
Jad Salhani
 
SOLID
SOLIDSOLID
The good, the bad and the SOLID
The good, the bad and the SOLIDThe good, the bad and the SOLID
The good, the bad and the SOLID
Frikkie van Biljon
 
Developing SOLID Code
Developing SOLID CodeDeveloping SOLID Code
Developing SOLID Code
Mark Niebergall
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
Jose Manuel Pereira Garcia
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
PROIDEA
 
Be pragmatic, be SOLID
Be pragmatic, be SOLIDBe pragmatic, be SOLID
Be pragmatic, be SOLID
Krzysztof Menżyk
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Codemotion
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
Daniel Fisher
 
Fatc
FatcFatc
OWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP ProgrammersOWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP Programmers
rjsmelo
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
Yi-Huan Chan
 
Solid principles
Solid principlesSolid principles
Solid principles
Toan Nguyen
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPmtoppa
 
Advanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in Laravel
Jonathan Behr
 
Make it SOLID!
Make it SOLID!Make it SOLID!
Make it SOLID!
Luís Cobucci
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Constanța Developers
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
Ionut Bilica
 

Similar to SOLID (20)

Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
Be pragmatic, be SOLID (at Boiling Frogs, Wrocław)
 
S.O.L.I.D. Principles
S.O.L.I.D. PrinciplesS.O.L.I.D. Principles
S.O.L.I.D. Principles
 
SOLID
SOLIDSOLID
SOLID
 
The good, the bad and the SOLID
The good, the bad and the SOLIDThe good, the bad and the SOLID
The good, the bad and the SOLID
 
Building Custom PHP Extensions
Building Custom PHP ExtensionsBuilding Custom PHP Extensions
Building Custom PHP Extensions
 
Developing SOLID Code
Developing SOLID CodeDeveloping SOLID Code
Developing SOLID Code
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
 
Be pragmatic, be SOLID
Be pragmatic, be SOLIDBe pragmatic, be SOLID
Be pragmatic, be SOLID
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
Fatc
FatcFatc
Fatc
 
OWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP ProgrammersOWASP TOP 10 for PHP Programmers
OWASP TOP 10 for PHP Programmers
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Dependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHPDependency Inversion and Dependency Injection in PHP
Dependency Inversion and Dependency Injection in PHP
 
Advanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in Laravel
 
Make it SOLID!
Make it SOLID!Make it SOLID!
Make it SOLID!
 
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
Andrei Iacob - SOLID: Strategies for Implementing Object–Oriented Design Prin...
 
SOLID Design Principles applied in Java
SOLID Design Principles applied in JavaSOLID Design Principles applied in Java
SOLID Design Principles applied in Java
 

More from PHPstokPHPstok

Jak ograniczyć używanie tablic w PHP.pptx
Jak ograniczyć używanie tablic w PHP.pptxJak ograniczyć używanie tablic w PHP.pptx
Jak ograniczyć używanie tablic w PHP.pptx
PHPstokPHPstok
 
Blaski i cienie pracy Project Managera.pptx
Blaski i cienie pracy Project Managera.pptxBlaski i cienie pracy Project Managera.pptx
Blaski i cienie pracy Project Managera.pptx
PHPstokPHPstok
 
Refaktoryzacja
RefaktoryzacjaRefaktoryzacja
Refaktoryzacja
PHPstokPHPstok
 
PHP 8.1
PHP 8.1PHP 8.1
Zarządzanie złożonością
Zarządzanie złożonościąZarządzanie złożonością
Zarządzanie złożonością
PHPstokPHPstok
 
Clean Code
Clean CodeClean Code
Clean Code
PHPstokPHPstok
 
Testy mutacyjne
Testy mutacyjneTesty mutacyjne
Testy mutacyjne
PHPstokPHPstok
 
Najczęstsze błędy początkujących programistów PHP
Najczęstsze błędy początkujących programistów PHPNajczęstsze błędy początkujących programistów PHP
Najczęstsze błędy początkujących programistów PHP
PHPstokPHPstok
 
Bezpieczeństwo aplikacji webowych
Bezpieczeństwo aplikacji webowychBezpieczeństwo aplikacji webowych
Bezpieczeństwo aplikacji webowych
PHPstokPHPstok
 
Wzorce projektowe w praktyce
Wzorce projektowe w praktyceWzorce projektowe w praktyce
Wzorce projektowe w praktyce
PHPstokPHPstok
 
Sztuka samodoskonalenia programisty
Sztuka samodoskonalenia programistySztuka samodoskonalenia programisty
Sztuka samodoskonalenia programisty
PHPstokPHPstok
 
Testy jednostkowe - PHPUnit
Testy jednostkowe - PHPUnitTesty jednostkowe - PHPUnit
Testy jednostkowe - PHPUnit
PHPstokPHPstok
 
Docker
DockerDocker
PSR czyli dobre praktyki programistyczne
PSR czyli dobre praktyki programistycznePSR czyli dobre praktyki programistyczne
PSR czyli dobre praktyki programistyczne
PHPstokPHPstok
 

More from PHPstokPHPstok (14)

Jak ograniczyć używanie tablic w PHP.pptx
Jak ograniczyć używanie tablic w PHP.pptxJak ograniczyć używanie tablic w PHP.pptx
Jak ograniczyć używanie tablic w PHP.pptx
 
Blaski i cienie pracy Project Managera.pptx
Blaski i cienie pracy Project Managera.pptxBlaski i cienie pracy Project Managera.pptx
Blaski i cienie pracy Project Managera.pptx
 
Refaktoryzacja
RefaktoryzacjaRefaktoryzacja
Refaktoryzacja
 
PHP 8.1
PHP 8.1PHP 8.1
PHP 8.1
 
Zarządzanie złożonością
Zarządzanie złożonościąZarządzanie złożonością
Zarządzanie złożonością
 
Clean Code
Clean CodeClean Code
Clean Code
 
Testy mutacyjne
Testy mutacyjneTesty mutacyjne
Testy mutacyjne
 
Najczęstsze błędy początkujących programistów PHP
Najczęstsze błędy początkujących programistów PHPNajczęstsze błędy początkujących programistów PHP
Najczęstsze błędy początkujących programistów PHP
 
Bezpieczeństwo aplikacji webowych
Bezpieczeństwo aplikacji webowychBezpieczeństwo aplikacji webowych
Bezpieczeństwo aplikacji webowych
 
Wzorce projektowe w praktyce
Wzorce projektowe w praktyceWzorce projektowe w praktyce
Wzorce projektowe w praktyce
 
Sztuka samodoskonalenia programisty
Sztuka samodoskonalenia programistySztuka samodoskonalenia programisty
Sztuka samodoskonalenia programisty
 
Testy jednostkowe - PHPUnit
Testy jednostkowe - PHPUnitTesty jednostkowe - PHPUnit
Testy jednostkowe - PHPUnit
 
Docker
DockerDocker
Docker
 
PSR czyli dobre praktyki programistyczne
PSR czyli dobre praktyki programistycznePSR czyli dobre praktyki programistyczne
PSR czyli dobre praktyki programistyczne
 

Recently uploaded

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

SOLID

  • 1. Programista PHP, Magento Developer Aurora Creation sp. z o.o. Łukasz Paliwoda luk.paliwoda@gmail.com l.paliwoda@auroracreation.com
  • 2. S O L I D
  • 3. “On the one hand, if the bricks aren’t well made, the architecture of the building doesn’t matter much. On the other hand, you can make a substantial mess with well-made bricks.” Robert C. Martin
  • 4. SOLID SOLID is a acronym for five design principles intended to make software designs more understandable, flexible and maintainable. ● Zebrane przez Robert C. Martin ● Nazwane przez Michael Feathers w 2004
  • 5. S R P O C P L S P I S P D I P Single Responsibility Principle Open/Closed Principle Liskov Substitution Principle Interface Segregation Principle Dependency Inversion Principle
  • 6. S O L I D
  • 7. SOLID Single Responsibility Principle “A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.”
  • 9. SOLID class Menu { public function getMenu() { $url = 'http://example.com/menu.xml'; $string = $this->download($url); $response = $this->parse($string); return $response; } private function parse($string) { /* some logic */ } private function download($url) { /* some logic */ } private function log($message) { /* some logic */ } } $menuDownloader = new Menu(); $menu = $menu->getMenu();
  • 10. SOLID class Menu { private $menuParser; private $contentProvider; public function __construct( XmlParser $menuParser, HttpClient $contentProvider ) { $this->menuParser = $menuParser; $this->contentProvider = $contentProvider; } public function getMenu() { $rawContent = $this->contentProvider->getRawContent(); $parsedMenu = $this->parser->parse($rawContent); return $parsedMenu; } } $parser = new XmlParser(); $httpClient = new HttpClient(); $menu = new Menu($parser, $httpClient); try { $menu = $menu->getMenu(); } catch (Exception $e) { echo $e->getMessage(); }
  • 11. S O L I D
  • 12. SOLID Open/Closed Principle "Software entities ... should be open for extension, but closed for modification."
  • 13. SOLID
  • 14. SOLID class Publisher { public function display($type) { switch($type) { case 'screen': /* some logic */ break; case 'rss': /* some logic */ break; } } } $publsher = new Publisher(); $publsher->display('screen'); $publsher->display('rss');
  • 15. SOLID interface PublisherInterface { public function getContent(); } class Publisher { public function display(PublisherInterface $publisher) { $publisher->getContent(); } } class ScreenPublisher implements PublisherInterface { public function getContent() { /* some logic */ } } class RssPublisher implements PublisherInterface { public function getContent() { /* some logic */ } }
  • 16. SOLID $publsher = new Publisher(); $screenPublisher = new ScreenPublisher(); $publsher->display($screenPublisher); $rssPublisher = new RssPublisher(); $publsher->display($rssPublisher); class PrintPublisher implements PublisherInterface { public function getContent() { /* some logic */ } } $printPublisher = new PrintPublisher(); $publsher->display($printPublisher);
  • 17. S O L I D
  • 18. SOLID Liskov Substitution Principle "Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program."
  • 19. SOLID
  • 20. SOLID class Ptak { public function lec() { /* some logic */ } } class Golab extends Ptak { } class Strus extends Ptak { public function lec() { throw new Exception('Not Implemented'); } } class Ptak { } class LatajacyPtak extends Ptak { public function lec() { /* some logic */ } } public class Golab extends LatajacyPtak { } public class Strus extends Ptak { }
  • 21. SOLID interface Jednoslad { public function jedz(); } class Rower implements Jednoslad { public function jedz(); } $notebook = new Rower(); $notebook->jedz(); class Motor implements Jednoslad { public function wlacz() { /* some logic */ } public function jedz() { /* some logic */ } } $tablet = new Motor(); $tablet->jedz(); // throw new Exception("You need to start the engine")
  • 22. S O L I D
  • 23. SOLID Interface Segregation Principle "Many client-specific interfaces are better than one general-purpose interface."
  • 24. SOLID
  • 25. SOLID interface FormatterInterface { public function toPDF($content); public function toXML($content); public function toJSON($content); } class Formatter implements FormatterInterface { public function toPDF($content) { throw new Exception('Not Implemented'); } public function toXML($content) { /* some logic */ } public function toJSON($content) { /* some logic */ } }
  • 26. SOLID interface PdfFormatterInterface { public function toPDF($content); } interface XmlFormatterInterface { public function toXML($content); } interface JsonFormatterInterface { public function toJSON($content); } class Formatter implements JsonFormatterInterface, XmlFormatterInterface { public function toJSON($content) { /* some logic */ } public function toXML($content) { /* some logic */ } }
  • 27. S O L I D
  • 28. SOLID Dependency Inversion Principle “Entities must depend on abstractions not on concretions.”
  • 29. SOLID
  • 30. SOLID
  • 31. SOLID class MysqlConnection { public function connect() { /* some logic */ } } class PasswordReminder { private $connection; public function __construct(MysqlConnection $connection) { $this->connection = $connection; } }
  • 32. SOLID interface DbConnectionInterface { public function connect(); } class MysqlConnection implements DbConnectionInterface { public function connect() { /* some logic */ } } class PasswordReminder { private $connection; public function __construct(DbConnectionInterface $connection) { $this->connection = $connection; } }
  • 33. Podsumowanie ● klasa powinna mieć jeden i tylko jeden powód do zmiany ● pozwól na zmianę zachowania systemu poprzez dodawanie nowego kodu, a nie modyfikowanie istniejącego ● buduj elementy tak aby były wzajemnie wymienne ● unikaj tworzenia zależności od elementów których nie potrzebujesz ● uniezależnij od siebie kod implementujący poszczególne warstwy

Editor's Notes

  1. programista PHP obecnie pracuję w firmie Aurora Creation sp. z o.o. zajmuję się pracą ze sklepami na platformie Magento tutaj są moje dane kontaktowe na wstępie chciałbym jeszcze dodać że nie mam doświadczenia w publicznych prezentacjach, dlatego proszę o wyrozumiałość oraz że będę posiłkował się notatkami
  2. kiedy szef poprosił aby powiedzieć kilka słów na PHPStock’u musiałem się zastanowić nad tematem o którym chciałbym powiedzieć jednym z popularnych tematów jest SOLID nie jest to temat nowy i na pewno wielu z was doskonale go zna Nie był on omawiany na PHPStock’u dlatego wypada nadrobić to niedopatrzenie Zaczynamy
  3. na początek cytat z jednej strony jeżeli cegiełki nie są solidnie zbudowane to architektura nie ma większego znaczenia. Z drugiej, można zrobić niezły bałagan z dobrze zbudowanych cegiełek to cytat z książki Roberta C. Martina (Uncle Bob) dość dobrze opisuje to z czym stykamy się na co dzień wiadomo że dobrą architekturę poznaje się nie po tym jak aplikacja działa w momencie puszczenia live a po tym jak znosi zmiany wymagań w trakcie wieloletniego procesu utrzymania czasem trzeba się dobrze nagłowić nad strukturą naszej aplikacji SOLID został stworzony aby pomóc nam tworzyć dobrą architekturę
  4. SOLID to akronim nazw 5 zasad traktujacych o dobrych praktykach tworzenia oprogramowania obiektowego Zostały zebrane przez Robert C. Martin pomiędzy końcówką lat ‘80 a początkiem lat 2000 nazwa SOLID została zaproponowana przez Michael’a Feather w mailu ok 2004 roku SOLID ma pomóc tworzyć kod który będzie dobrze znosił zmiany, będzie łatwiejszy w utrzymaniu i prostszy do zrozumienia
  5. SOLID to tak naprawdę trochę więcej liter jak wspomniałem to zbiór 5 zasad Nie są one czymś czego bezwzględnie trzeba przestrzegać, ale ich przestrzeganie pozwala budowa lepsze aplikacje teraz przejdziemy do omówienia poszczególnych reguł
  6. Każdy moduł/klasa powinny mieć jeden i tylko jeden powód do zmiany. Każda klasa powinna odpowiadać przed jednym aktorem systemu, tak aby zmiany wymagań jednego aktora nie wpływały na to jak działa aplikacja dla innych aktorów
  7. Załóżmy że mamy w firmie dział kadr, księgowości oraz techniczny. Programując system POWIĄZALIŚMY klasę Emploee z każdym z tych działów. Księgowość -> calculatepay Kadry -> reportHours Techniczny -> save W pewnym momencie księgowość uznała że trzeba zmienić sposób obliczania godzin Programista wprowadza zmiany w klasie regularHours Prowadzi to do niezamierzonej zmiany funkcjonowania metody reportHours
  8. Przykład kodu Klasa Menu Odpowiedzialna za pobranie i przeparsowanie zasobów z jakiegoś zewnętrznego źródła Na załączonym przykładzie klasa posiada metody Download - odpowiedzialną za pobranie danych Parse - odpowiedzialną za przeparsowanie pobranych danych Log - odpowiedzialną za zapisanie błędu Na tym przykładzie jedna klasa ma wiele odpowiedzialności W związku z tym zmiana dowolnej z tych funkcji może powodować błędy w pozostałych
  9. Na kolejnym przykładzie Poszczególne odpowiedzialności zostały wydzielone Do klas XmlParser oraz HttpClient Błędy natomiast są zwracane jako wyjątki Dzięki temu poszczególne funkcjonalności zostały rozdzielone I zmiana w klasie XmlParser nie wpłynie na działanie pozostałych elementów
  10. Otwarty na rozszerzenie / zamknięty na modyfikację Reguła rozsławiona przez Bertrand Meyer w latach ‘80 “Jeżeli oprogramowanie ma pozwalać na łatwe wprowadzanie zmian, to musi zostać zaprojektowane tak, żeby pozwalało na zmianę zachowania systemu poprzez dodawanie nowego kodu, a nie modyfikowanie istniejącego.”
  11. Załóżmy że piszemy klasę prezentującą jakąś treść, jakiś kontent Na początku ma ona być wyświetlane na ekranie Po pewnym czasie wymagania stawiane przed naszą klasą są rozszerzane i ma obsłużyć również drukarkę Dodajemy ify Po kolejnej zmianie wymagań klasa ma obsłużyć również kanał RSS Dodajemy ify Każda zmiana wymagała od nas powrotu do kodu i jego zmodyfikowania Uniknęlibyśmy tego gdybyśmy logikę odpowiedzialną za prezentacje danych wydzielili do oddzielnych klas A klasę menu zaprojektowali tak aby ich używała
  12. Przykład kodu Mamy klasę Publisher której zadaniem jest zaprezentowanie informacji w odpowiednim formacie Logika odpowiedzialna za sformatowanie danych została zawarta w prostym Switch’u Zmusza nas to do zmodyfikowania tego swicha za każdym razem gdy chcemy dodać nowy format
  13. Kolejny przykład definiuje interfejs Oraz zmusza klasę Publisher do pracy z interfejsem Logikę odpowiedzialną za formatowanie umieszczamy w klasach implementujących nasz interfejs
  14. Sposób w jaki mają zostać sformatowane dane przekazujemy z zewnątrz Dzięki temu dodanie nowego formatu ogranicza się do utworzenia klasy implementującej nasz interfejs W taki sposób uniknęliśmy modyfikowania istniejącego kodu przy dodawaniu nowych funkcji
  15. Powinna istnieć możliwość zastąpienia klas ich potomkami w taki sposób aby nie psuło to aplikacji Reguła liskov mówi nam o tym że elementy aplikacji powinny być na tyle wymienialne że możemy wziąć sobie jedną klasę, wstawić w to miejsce inną i wszystko powinno działać
  16. Załóżmy że do restauracji codziennie o 8 rano przywożą owoce, dzięki temu od tej godziny kucharz może przygotowywać dania gościom Któregoś dnia właściciel podpisał umowę z innym dostawcą, ale zapomniał powiedzieć mu że warzywa mają przyjechać o 8 Firma nie dostarczyła warzyw, kucharz nie miał jak przygotować potraw gościom Stało się tak bo został złamany kontrakt Gydby dostawa przyjechała na czas to wszystko działało by jak dawniej
  17. Unikaj tworzenia zależności od elementów których nie potrzebujesz Zgodnie z tą zasadą - tworzone interfejsy powinny zawierać minimalną liczbę deklaracji metod. Mniejsza ilość metod może być zrekompensowana możliwością dziedziczenia wielu interfejsów
  18. Najtrudniej było mi wymyślić przykład do tej zasady Każdy z nas ma klucze Ja swoje nosze w kieszeni
  19. Gdy interfejs ma wiele metod To implementując go musimy zaimplementować wszystkie jego metody Nie da się wydzielić kilku z nich Tak jak na przykładzie - musimy zaimplementować niewspieraną metodę toPDF
  20. Jeżeli natomiast mamy kilka interfejsów zawierających mniejszą liczbę metod To możemy dowolnie kształtować to co implementuje nasza klasa
  21. Klasy powinny zależeć od abstrakcji nie od konkretnych implementacji.
  22. Jeżeli Klasa 2 zależy od Klasy 1 to nie mamy możliwości zmienić jej implementacji Jeżeli natomiast Klasa 2 Będzie zależeć od interfejsu To możemy swobodnie podmienić Klasę 1 na inną klasę implementującą ten sam interfejs.
  23. nie mogłem się powstrzymać aby umieścić tu ten rysunek to ilustracja do wiersza Juliama Tuwima a nie do popularnego teleturnieju i z rzepki nie wystrzelą pieniążki Kto pamięta ten wiersz to wie że w ostatniej zwrotce wszystkie postacie leżały na ziemi Tak samo i my możemy leżeć jeżeli szef poprosi o wymianę klasy która leży w fundamentach systemu A która nie posiada abstrakcji
  24. Dla przykładu Klasa PasswordReminder zależy od MysqlConnection To znaczy że do konstruktora PasswordReminder zawsze musimy wrzucić MysqlConnection
  25. Jeżeli jednak utworzymy interfejs DbConnectionInterface I klasę PasswordReminder uzależnimy od tego interfejsu To do konstruktora będziemy mogli podać dowolną klasę implementującą ten interfejs. Innymi słowy “Nasza klasa klasę PasswordReminder będzie niezależna od konkretnej implementacji interfejsu DbConnectionInterface” Zasada odwracania zależności to zwieńćzenie całego SOLID. Zachęca do uzależniania się od abstrakcji, a nie od konkretnych implementacji rozwiązań.