Hasan Setiawan

Write, write, write give your wings on code!

Follow me on GitHub

# 3 # S.O.L.I.D Object Oriented Design

In PHP OOP we already know about Dependency Injection, or some design pattern like Factory, singleton. And how about SOLID?

SOLID stands for

Single responsibility principle
Open closed principle
Liskov substitution principle
Interface segregation principle
Dependency inversion principle

# 3 # Liskov substitution principle

We’ve been taught that the whole world is made of objects and that we are supposed to model our software after the real world.

The Liskov Substitution Principle says that “Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it” (Uncle Bob’s paraphrase).

              
                  //Liskov Substitution Principle
                  class Rectangle
                  {
                    public function setWidth($w) { $this->width = $w; }
                    public function setHeight($h) { $this->height = $h; }
                    public function getArea() { return $this->height * $this->width; }
                  }


                  class Square extends Rectangle
                  {
                    public function setWidth($w) { $this->width = $w; $this->height = $w; }
                    public function setHeight($h) { $this->height = $h; $this->width = $h; }
                  }


                  //and we create our function to calculate classes :
                  function areaOfRectangle() {
                    $rectangle = new Rectangle();
                    $r->setWidth(7); $r->setHeight(3);
                    $r->getArea(); // 21
                  }


                  //as the LSP says, we should be able to change Rectangle by Square
                  function areaOfRectangle() {
                    $rectangle = new Square();
                    $r->setWidth(7); $r->setHeight(3);
                    $r->getArea(); // 9
                  }