SlideShare a Scribd company logo
1 of 35
Design Patterns
    Daniel Waligóra
   Wrocław 09/01/2012




           1
Bibliography
•   Martin Fowler,Patterns of Enterprise Appication Architecture

•   Matt Zandstra , PHP5 Objects, Patters, and Practice

•   http://www.ustream.tv - New York PHP channel

•   Symfony Live Berlin 2012 - https://joind.in/event/view/1114

•   http://scholar.google.pl

•   http://pzielinski.com



                               2
Gang of Four




     3
Breakdown Design
    Patterns by GoF
                     Design Patterns




 creational            structural      behavioral
- abstract factory    - decorator      - observer
- builder             - facade         - strategy
- prototype           - composite      - command
                              4
5
6
Implementation related
    to the context
  programming
                         scalability
    language
                           testable
   modularity
                      (integration test)

 time-consuming        size of project



                  7
Design patterns
IS NOT related          Context IS
      to the          related to the
 programming          programming
    language             language




                  8
1.
2.
             Transaction Script
      class Hotel  
      {   
3.        private    
4.            $_gateway;

5.        public function __construct(Data_Access_Gateway $gateway)    
6.        {    
7.            $this->_gateway = $gateway;    
8.        }    
9.      
10.       public function bookRoom($userId, $fromDate, $toDate)    
11.       {    
12.           $roomId = $this->_gateway->_getRoomIdBetweenDates($fromDate, $toDate);    
13.     
14.           if (!$roomId) {    
15.               return false;    
16.           }    
17.     
18.           $days = $this->_getAmountOfDays($fromDate, $toDate);    
19.     
20.           if ($days < = 7) {  
21.               $price = $days * 100;  
22.           } else {   
23.               $price = $days * 80;  
24.           }  
25.             
26.           $data = array(  
27.               'userId' => $userId,    
28.               'roomId' => $roomId,  
29.               'fromDate' => $fromDate,    
30.               'toDate' => $toDate,    
31.               'price' => $price,    
32.           );    
33.     
34.           $bookingId = $this->_gateway->insert('bookings', $data);    
35.     
36.           return $bookingId;    
37.       }    
38.   } 

                                                              9
Transaction Script
Advantages:                      Disadvantages:

•   simple procedural model      •   difficult to maintenance

•   works well with a simple     •   code duplication
    data access layer

•   easy implementation of use
    cases




                           10
1.
               Table Module #1
     class Hotel  
2.   {    
3.       public function __construct(Data_Access_Gateway $gateway, Booking $booking)    
•        {    
•            $this->_gateway = $gateway;  
•            $this->_booking = $booking;  
•        }    
•      
•        public function bookRoom($userId, $fromDate, $toDate)    
•        {    
•            $roomId = $this->_booking->getRoomBetweenDates($fromDate, $toDate);  
•      
•            if (!$roomId) {    
•                return false;    
•            }    
•      
•            $days = $this->_getAmountOfDays($fromDate, $toDate);    
•      
•            if ($days < = 7) {  
•                $price = $days * 100;  
•            } else {   
•                $price = $days * 80;  
•            }  
•              
•            $bookingId = $this->_booking-
     >addBooking($userId, $roomId, $fromDate, $toDate, $price);    
•      
•            return $bookingId;    
•        }    
•    }  
•      

                                                11
Table Module #2
1. class Booking  
2. {    
3.     public function __construct(Data_Access_Gateway $gateway)    
4.     {    
5.         $this->_gateway = $gateway;    
6.     }  
7.       
8.     public function getRoomBetweenDates($dateFrom, $dateTo)  
9.     {  
10.        return $this->_gateway->getRoomBetweenDates($dateFrom, $dateTo);  
11.    }  
12.      
13.    public function addBooking($userId, $roomId, $fromDate, $toDate, $price)    
14.    {    
15.        $data = array(  
16.            'userId' => $userId,    
17.            'roomId' => $roomId,  
18.            'fromDate' => $fromDate,    
19.            'toDate' => $toDate,    
20.            'price' => $price,    
21.        );    
22.  
23.        $bookingId = $this->_gateway->insert('bookings', $data);    
24.  
25.        return $bookingId;    
26.    }    
27.}  


                                           12
Table Module vs
     Transaction Script
Advantages:                       Disadvantages:
•   less duplication              •   weak support for
                                      polymorphism
•   encapsulation
                                  •   no support ORM
•   more organized and
    structured code

•   easy implementation by
    technology support

                             13
Domain Model #1
1. class Hotel  
2. {    
3.     protected $_hotelId;  
4.     protected $_rooms;  
5.       
6.     public function bookRoom(User $user, $fromDate, $toDate)    
7.     {    
8.         $room = $this->_getRoomBetweenDates($fromDate, $toDate);  
9.   
10.         if (is_null($room)) {    
11.             return false;    
12.         }    
13.   
14.         $booking = $room->bookRoom(User $user, $fromDate, $toDate);  
15.   
16.         return $booking;    
17.     }  
18. }  
19.   
20. class Room  
21. {  
22.     protected $_roomId;  
23.     protected $_bookings = array();  
24.       
25.     public function bookRoom(User $user, $fromDate, $toDate)  
26.     {  
27.         $days = $this->_getAmountOfDays($fromDate, $toDate);  
28.           
29.         if ($days < = 7) {  
30.             $booking = new Booking($user, new ShortBookingStrategy($user, $days));  
31.         } else {   
32.             $booking = new Booking($user, new NormalBookingStrategy($user, $days));  
33.         }  
34.           
35.         return $booking;  
36.     }  
37. } 


                                                           14
Domain Model #2
1. class NormalBookingPriceStrategy extends BookingPriceStrategy  
2. {  
3.     public function getPrice()  
4.     {  
5.         $price = $this->_days * 80;  
6.           
7.         if ($this->_user->isLoyal()) {  
8.             $price = $price / 2;  
9.         }  
10.          
11.        return $price;  
12.    }  
13.}  
14.  
15.class ShortBookingPriceStrategy extends BookingPriceStrategy  
16.{    
17.    public function getPrice()  
18.    {  
19.        return $this->_days * 100;  
20.    }  
21.}



                                       15
Domain Model vs
     Procedural Pattern
                •                       time-consuming
                                        implementation

Advantages:                           • additional patterns
                                      Disadvantages:

•   prevents logic duplication        - ORM
•   more code readability             - data source
•   independence from the data
    source

•   much easier to unit test

                                 16
SUMMARY
 programming
                              scalability
   language

   modularity              time-consuming

     testable
                            size of project
(integration test)

          skill of the developers

                     17
Don’t be STUPID,
GRASP SOLID!


       18
Sorry, but your code is
       STUPID!


           19
•S   ingleton
1.class DB 
2.{  
3.    private static $instance;

4.    public static function getInstance()


            Dupleton ?
5.    {  
6.        if(!isset(self::$instance)) {  
7.            self::$instance = new self;  
8.        }  
9.          
10.        return self::$instance;  
11.    }  
12.}  



                       21
                       20
•S
1.class DB 
2. {  
            ingleton (ctd)
3.     private static $instance;

•       public static function getInstance()
•       {  
•           if(!isset(self::$instance)) {  
•               self::$instance = new self;  
•           }  
•             
•           return self::$instance;  
•       }  
•   }  

• class Order 
• {  
•     protected $db;

•       public function __construct()
•       {  
•           $this->db = DB::getInstance();           
•       }  
•   }



                                       21
•S   ingleton (ctd)


       1.class DB 
       2. {
       3.     //body
       4. }

       5.class Order 
       6. {  
       •     protected $db;

       •       public function __construct(DB $db)
       •       {  
       •           $this->db = $db;           
       •       }  
       •   }




                               22
•T      ight Coupling

1.Order::buy();

1.class House 
2. {
3.     public function __construct()
•     {
•          $this->door = new Door();
•          $this->window = new Window();
•     }
• }
1.class House 
2. {
3.     public function __construct(Door $door, Window 
   $window)
•     {
•          $this->door = $door;
•          $this->window = $window;
•     }
• }



                                   23
•U   ntestable Code



        I don’t
        have a
         time!




                      24
•P   remature Optimization



    Never Make Code
  Faster Than Necessary,
  Something Important Is
 Always Lost When You Do



                    25
•P   remature Optimization (ctd)




Performance
                              20% of code
 problems




                     26
•I ndescriptive Naming


char * strpbrk ( const char *, const char * ); 



                              ?




                      27
•I ndescriptive Naming (ctd)




Code is Read Far More Often Than Written




                      28
•Duplication



     DRY (Don’t Repeat Yourself!)


     KISS (Keep It Smile, Stupid!)




                   29
•S
 ingleton


•Tight Coupling


•Untestable Code


•P
 remature Optimization


•I
 ndescriptive Naming


•Duplication
                   30
•S
 ingle Responsibility Principle


•O pen/Closed Principle


•L
 iskov Substitution Principle


•I
 nterface Segregation Principle


•Dependency Inversion Principle

                   31
32
Test Driven-
Development




     33
Advantages of Design
      Pattern?
• speed up the development process,
• helps to prevent issues that can cause
  major problems,
• patterns allow developers to communicate
  using well-known, well understood names
  for software interactions


                     34
EoT
Thank You

    35

More Related Content

What's hot

The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable CodeBaidu, Inc.
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019julien pauli
 
Webit expo Standard Product
Webit expo Standard ProductWebit expo Standard Product
Webit expo Standard ProductBoji Ditcheva
 
Object::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your CodeObject::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your CodeWorkhorse Computing
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askAndrea Giuliano
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsSergio Acosta
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)brian d foy
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeNeil Crookes
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
 
Introduction to DI(C)
Introduction to DI(C)Introduction to DI(C)
Introduction to DI(C)Radek Benkel
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Mail.ru Group
 

What's hot (20)

C++ prgms 3rd unit
C++ prgms 3rd unitC++ prgms 3rd unit
C++ prgms 3rd unit
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
Java script
Java scriptJava script
Java script
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019Doctrine with Symfony - SymfonyCon 2019
Doctrine with Symfony - SymfonyCon 2019
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
Webit expo Standard Product
Webit expo Standard ProductWebit expo Standard Product
Webit expo Standard Product
 
Object::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your CodeObject::Franger: Wear a Raincoat in your Code
Object::Franger: Wear a Raincoat in your Code
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to ask
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
The zen of async: Best practices for best performance
The zen of async: Best practices for best performanceThe zen of async: Best practices for best performance
The zen of async: Best practices for best performance
 
Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and Bindings
 
Metaprogramming in ES6
Metaprogramming in ES6Metaprogramming in ES6
Metaprogramming in ES6
 
CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)CGI::Prototype (NPW 2006)
CGI::Prototype (NPW 2006)
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better Code
 
Building a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing StrategiesBuilding a Pyramid: Symfony Testing Strategies
Building a Pyramid: Symfony Testing Strategies
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Introduction to DI(C)
Introduction to DI(C)Introduction to DI(C)
Introduction to DI(C)
 
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
 

Viewers also liked

http://commercialinsurance.nearneworleansarea.com/
http://commercialinsurance.nearneworleansarea.com/http://commercialinsurance.nearneworleansarea.com/
http://commercialinsurance.nearneworleansarea.com/dkfjslk
 
Derek berger december 3 2012 final presentation
Derek berger december 3 2012 final presentationDerek berger december 3 2012 final presentation
Derek berger december 3 2012 final presentationderekjberger
 
130409セミプロに駆逐されるプロの構図
130409セミプロに駆逐されるプロの構図130409セミプロに駆逐されるプロの構図
130409セミプロに駆逐されるプロの構図Tomohiko Suwa
 
Gender communication in social institutions
Gender communication in social institutionsGender communication in social institutions
Gender communication in social institutionskathleenjones2012
 
El so mòdul 1
El so   mòdul 1El so   mòdul 1
El so mòdul 1montsets
 

Viewers also liked (15)

http://commercialinsurance.nearneworleansarea.com/
http://commercialinsurance.nearneworleansarea.com/http://commercialinsurance.nearneworleansarea.com/
http://commercialinsurance.nearneworleansarea.com/
 
Derek berger december 3 2012 final presentation
Derek berger december 3 2012 final presentationDerek berger december 3 2012 final presentation
Derek berger december 3 2012 final presentation
 
130409セミプロに駆逐されるプロの構図
130409セミプロに駆逐されるプロの構図130409セミプロに駆逐されるプロの構図
130409セミプロに駆逐されるプロの構図
 
Galau karna Cinta
Galau karna CintaGalau karna Cinta
Galau karna Cinta
 
GALAU & CINTA
GALAU & CINTAGALAU & CINTA
GALAU & CINTA
 
Tik pp
Tik ppTik pp
Tik pp
 
Opk things nenden
Opk things   nendenOpk things   nenden
Opk things nenden
 
Love is
Love isLove is
Love is
 
Gender communication in social institutions
Gender communication in social institutionsGender communication in social institutions
Gender communication in social institutions
 
Cinta
Cinta Cinta
Cinta
 
Starbucks
StarbucksStarbucks
Starbucks
 
El so mòdul 1
El so   mòdul 1El so   mòdul 1
El so mòdul 1
 
Agile methodology
Agile methodologyAgile methodology
Agile methodology
 
The silent way
The silent wayThe silent way
The silent way
 
Basmati rice case study
 Basmati rice case study Basmati rice case study
Basmati rice case study
 

Similar to Design Patterns

Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design PatternsCode Gentlemen
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)Markus Eisele
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterMithun T. Dhar
 
DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)Oleg Zinchenko
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and DesktopElizabeth Smith
 
PHP Development With MongoDB
PHP Development With MongoDBPHP Development With MongoDB
PHP Development With MongoDBFitz Agard
 
PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)MongoSF
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormMichelangelo van Dam
 
Blunt Umbrellas Website Showcase
Blunt Umbrellas Website ShowcaseBlunt Umbrellas Website Showcase
Blunt Umbrellas Website ShowcaseGareth Hall
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоWebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоGeeksLab Odessa
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIsJulian Viereck
 
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!Kacper Gunia
 

Similar to Design Patterns (20)

Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Hexagonal architecture
Hexagonal architectureHexagonal architecture
Hexagonal architecture
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 
Building High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 FirestarterBuilding High Perf Web Apps - IE8 Firestarter
Building High Perf Web Apps - IE8 Firestarter
 
DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)DDD on example of Symfony (SfCampUA14)
DDD on example of Symfony (SfCampUA14)
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
PHP Development With MongoDB
PHP Development With MongoDBPHP Development With MongoDB
PHP Development With MongoDB
 
PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)PHP Development with MongoDB (Fitz Agard)
PHP Development with MongoDB (Fitz Agard)
 
What is DDD and how could it help you
What is DDD and how could it help youWhat is DDD and how could it help you
What is DDD and how could it help you
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Node azure
Node azureNode azure
Node azure
 
Fatc
FatcFatc
Fatc
 
Blunt Umbrellas Website Showcase
Blunt Umbrellas Website ShowcaseBlunt Umbrellas Website Showcase
Blunt Umbrellas Website Showcase
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег ЗинченкоWebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
 
Implementing New Web
Implementing New WebImplementing New Web
Implementing New Web
 
Implementing new WebAPIs
Implementing new WebAPIsImplementing new WebAPIs
Implementing new WebAPIs
 
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
Domain-driven Design in PHP and Symfony - Drupal Camp Wroclaw!
 

Design Patterns

  • 1. Design Patterns Daniel Waligóra Wrocław 09/01/2012 1
  • 2. Bibliography • Martin Fowler,Patterns of Enterprise Appication Architecture • Matt Zandstra , PHP5 Objects, Patters, and Practice • http://www.ustream.tv - New York PHP channel • Symfony Live Berlin 2012 - https://joind.in/event/view/1114 • http://scholar.google.pl • http://pzielinski.com 2
  • 4. Breakdown Design Patterns by GoF Design Patterns creational structural behavioral - abstract factory - decorator - observer - builder - facade - strategy - prototype - composite - command 4
  • 5. 5
  • 6. 6
  • 7. Implementation related to the context programming scalability language testable modularity (integration test) time-consuming size of project 7
  • 8. Design patterns IS NOT related Context IS to the related to the programming programming language language 8
  • 9. 1. 2. Transaction Script class Hotel   {    3.     private     4.         $_gateway; 5.     public function __construct(Data_Access_Gateway $gateway)     6.     {     7.         $this->_gateway = $gateway;     8.     }     9.    10.     public function bookRoom($userId, $fromDate, $toDate)     11.     {     12.         $roomId = $this->_gateway->_getRoomIdBetweenDates($fromDate, $toDate);     13.    14.         if (!$roomId) {     15.             return false;     16.         }     17.    18.         $days = $this->_getAmountOfDays($fromDate, $toDate);     19.    20.         if ($days < = 7) {   21.             $price = $days * 100;   22.         } else {    23.             $price = $days * 80;   24.         }   25.            26.         $data = array(   27.             'userId' => $userId,     28.             'roomId' => $roomId,   29.             'fromDate' => $fromDate,     30.             'toDate' => $toDate,     31.             'price' => $price,     32.         );     33.    34.         $bookingId = $this->_gateway->insert('bookings', $data);     35.    36.         return $bookingId;     37.     }     38. }  9
  • 10. Transaction Script Advantages: Disadvantages: • simple procedural model • difficult to maintenance • works well with a simple • code duplication data access layer • easy implementation of use cases 10
  • 11. 1. Table Module #1 class Hotel   2. {     3.     public function __construct(Data_Access_Gateway $gateway, Booking $booking)     •     {     •         $this->_gateway = $gateway;   •         $this->_booking = $booking;   •     }     •    •     public function bookRoom($userId, $fromDate, $toDate)     •     {     •         $roomId = $this->_booking->getRoomBetweenDates($fromDate, $toDate);   •    •         if (!$roomId) {     •             return false;     •         }     •    •         $days = $this->_getAmountOfDays($fromDate, $toDate);     •    •         if ($days < = 7) {   •             $price = $days * 100;   •         } else {    •             $price = $days * 80;   •         }   •            •         $bookingId = $this->_booking- >addBooking($userId, $roomId, $fromDate, $toDate, $price);     •    •         return $bookingId;     •     }     • }   •    11
  • 12. Table Module #2 1. class Booking   2. {     3.     public function __construct(Data_Access_Gateway $gateway)     4.     {     5.         $this->_gateway = $gateway;     6.     }   7.        8.     public function getRoomBetweenDates($dateFrom, $dateTo)   9.     {   10.        return $this->_gateway->getRoomBetweenDates($dateFrom, $dateTo);   11.    }   12.       13.    public function addBooking($userId, $roomId, $fromDate, $toDate, $price)     14.    {     15.        $data = array(   16.            'userId' => $userId,     17.            'roomId' => $roomId,   18.            'fromDate' => $fromDate,     19.            'toDate' => $toDate,     20.            'price' => $price,     21.        );     22.   23.        $bookingId = $this->_gateway->insert('bookings', $data);     24.   25.        return $bookingId;     26.    }     27.}   12
  • 13. Table Module vs Transaction Script Advantages: Disadvantages: • less duplication • weak support for polymorphism • encapsulation • no support ORM • more organized and structured code • easy implementation by technology support 13
  • 14. Domain Model #1 1. class Hotel   2. {     3.     protected $_hotelId;   4.     protected $_rooms;   5.        6.     public function bookRoom(User $user, $fromDate, $toDate)     7.     {     8.         $room = $this->_getRoomBetweenDates($fromDate, $toDate);   9.    10.         if (is_null($room)) {     11.             return false;     12.         }     13.    14.         $booking = $room->bookRoom(User $user, $fromDate, $toDate);   15.    16.         return $booking;     17.     }   18. }   19.    20. class Room   21. {   22.     protected $_roomId;   23.     protected $_bookings = array();   24.        25.     public function bookRoom(User $user, $fromDate, $toDate)   26.     {   27.         $days = $this->_getAmountOfDays($fromDate, $toDate);   28.            29.         if ($days < = 7) {   30.             $booking = new Booking($user, new ShortBookingStrategy($user, $days));   31.         } else {    32.             $booking = new Booking($user, new NormalBookingStrategy($user, $days));   33.         }   34.            35.         return $booking;   36.     }   37. }  14
  • 15. Domain Model #2 1. class NormalBookingPriceStrategy extends BookingPriceStrategy   2. {   3.     public function getPrice()   4.     {   5.         $price = $this->_days * 80;   6.            7.         if ($this->_user->isLoyal()) {   8.             $price = $price / 2;   9.         }   10.           11.        return $price;   12.    }   13.}   14.   15.class ShortBookingPriceStrategy extends BookingPriceStrategy   16.{     17.    public function getPrice()   18.    {   19.        return $this->_days * 100;   20.    }   21.} 15
  • 16. Domain Model vs Procedural Pattern • time-consuming implementation Advantages: • additional patterns Disadvantages: • prevents logic duplication - ORM • more code readability - data source • independence from the data source • much easier to unit test 16
  • 17. SUMMARY programming scalability language modularity time-consuming testable size of project (integration test) skill of the developers 17
  • 19. Sorry, but your code is STUPID! 19
  • 20. •S ingleton 1.class DB  2.{   3.    private static $instance; 4.    public static function getInstance() Dupleton ? 5.    {   6.        if(!isset(self::$instance)) {   7.            self::$instance = new self;   8.        }   9.           10.        return self::$instance;   11.    }   12.}   21 20
  • 21. •S 1.class DB  2. {   ingleton (ctd) 3.     private static $instance; •     public static function getInstance() •     {   •         if(!isset(self::$instance)) {   •             self::$instance = new self;   •         }   •            •         return self::$instance;   •     }   • }   • class Order  • {   •     protected $db; •     public function __construct() •     {   •         $this->db = DB::getInstance();            •     }   • } 21
  • 22. •S ingleton (ctd) 1.class DB  2. { 3.     //body 4. } 5.class Order  6. {   •     protected $db; •     public function __construct(DB $db) •     {   •         $this->db = $db;            •     }   • } 22
  • 23. •T ight Coupling 1.Order::buy(); 1.class House  2. { 3.     public function __construct() •     { •          $this->door = new Door(); •          $this->window = new Window(); •     } • } 1.class House  2. { 3.     public function __construct(Door $door, Window  $window) •     { •          $this->door = $door; •          $this->window = $window; •     } • } 23
  • 24. •U ntestable Code I don’t have a time! 24
  • 25. •P remature Optimization Never Make Code Faster Than Necessary, Something Important Is Always Lost When You Do 25
  • 26. •P remature Optimization (ctd) Performance 20% of code problems 26
  • 28. •I ndescriptive Naming (ctd) Code is Read Far More Often Than Written 28
  • 29. •Duplication DRY (Don’t Repeat Yourself!) KISS (Keep It Smile, Stupid!) 29
  • 30. •S ingleton •Tight Coupling •Untestable Code •P remature Optimization •I ndescriptive Naming •Duplication 30
  • 31. •S ingle Responsibility Principle •O pen/Closed Principle •L iskov Substitution Principle •I nterface Segregation Principle •Dependency Inversion Principle 31
  • 32. 32
  • 34. Advantages of Design Pattern? • speed up the development process, • helps to prevent issues that can cause major problems, • patterns allow developers to communicate using well-known, well understood names for software interactions 34