in design pattern php object oriented programming oop cleanc code programming ~ read.

Strategy Design Pattern in PHP

In this post we are going to talk about Strategy Pattern in Object Oriented Programming.

What is Strategy Pattern?

Strategy Pattern encapsulates algorithms into classes. If you see a lot of conditional statement in order to perform different algorithms then this is exactly what Strategy Design Pattern is for.

That's enough of talking let's see some real code.

Demo

We are going to use Strategy Pattern to create different types of credit cards.

First let's create a class called CreditCard.

<?php

class CreditCard {  
    private $number;
    private $date;
    private $cvv;
    private $strategy;

    public function __construct(ValidationStrategy $strategy) {
       $this->strategy = $strategy;
    }

    public function isValid() {
        return $this->strategy->isValid($this);
    }
}

(CreditCard)

Next let's create an abstract class called ValidationStrategy.

<?php

abstract class ValidationStrategy {  
    abstract protected function isValid(CreditCard $creditCard);
}

(ValidationStrategy)

Now let's create our concrete instances using ValidationStrategy class.

Let's create a class called AmexStrategy.

<?php

class AmexStrategy extends ValidationStrategy {  
    public function isValid() {
        // Amex Algorithm
        return true;
    }
}

(AmexStrategy)

Another one called VisaStrategy.

class VisaStrategy extends ValidationStrategy {  
    public function isValid() {
        // Visa Algorithm
        return true;
    }
}

(VisaStrategy)

Finally, let's use it in our code.

<?php

$amexCard = new CreditCard(new AmexStrategy());
$amexCard->isValid(); // return true

$visaCard = new CreditCard(new VisaStrategy());
$visaCard->isValid(); // return true

End

As you can see here that we put the algorithms that verifying credit cards into individual class which eliminate conditional statements and promote good object-oriented practice.

As always if you have any opinions or ideas please leave it below. Thanks.

comments powered by Disqus