Friday 3 May 2013

Thinking OOP in php ( Part 1 )

This is part 1 of thinking OOP ( some people even say OOPs ) in php series. The aim of this series is to pick up some real world problem ( kinda ) and then to solve it using Object Oriented Concepts and Design Patterns and Principles. Let's get started then.

Problem
Let's assume that you are working as a programmer in a company and a new requirement has just come up. Your page will be passed a parameter called color and based on that color you have to display a button ( obviously of that color ).

Solutoin 1
Let's review our code for some potential problems.

  1. The logic of how our button is displayed is naked. ( We will have to modify this script file if we decide that our color should begin with capital letter )
  2. The logic of what to do based on the value of parameter is tightly coupled with the client ( For example, if in some other script file we want to reuse the button display logic we will end up copying these lines or do an include or whatever )
Let's address problem number 1 first. We can hide the implementation of button by creating a class. Lets create classes called BlueButton and GreenButton.
Solutoin 2
Our Solution 2 looks slightly better than solution 1. We have solved the problem of implementation of button being naked by encapsulating it in to a class. However, we still have logic of which class to instantiate and knowledge of all the classes ( BlueButton, GreenButton and all the future ButtonClasses ) coupled in the client. To solve this issue, we are going to use Factory Design Pattern.

Builder In our case, ConcreteProduct is Button class. We do not have an AbstractProduct class but we will create one.
Solutoin 3 And that's basically it. We have successfully applied design pattern and OOP concept ( encapsulation ) to the given problem. Next time I will cover a new problem and one more design pattern. Cheers

No comments:

Post a Comment