Minggu, 08 Maret 2015

PHP Object Oriented Programming for Newbies

This article analyzes the reasons of using Object Oriented Programming for PHP newcomers. In his opinion anyone can found thousands of tutorials for Object Oriented PHP and Object Oriented Programming. But what about a different… newbie PHP approach?
object-oriented-chaos
My approach is to convenience newcomers from PHP background to learn Object Oriented Programming. As there are plenty of tutorials out there, I will try to explain only some basic things about OO Programming with a simple way.
The only requirements to actually read this article is to have a very first impression of PHP. Even if the only thing that you have learned so far is:
<?php echo "hello World!"; ?>
You should still learn how to program with Object Oriented Programming. Crazy, huh? Why from using the simple functions in PHP we should learn to write code like the code below?
namespace Foo\Bar {
    class Baz implements BamAwareInterface {
        public $bam;
        public function setBam(Bam $bam){
            $this->bam = $bam;
        }
    }
    class Bam {
    }
    interface BamAwareInterface
    {
        public function setBam(Bam $bam);
    }
}
Well let’s start then…

The paradox

I have many years experience in Object Oriented programming with PHP but with Java as well. I remember my very first approach at the university with Object Oriented Programming and Java. They didn’t teach us WHY to use Object Oriented programming, they just teach us that THIS is Object Oriented Programming and some ways that we can use it.
The paradox about that is that from the basic steps of programming you need to jump to Object Oriented programming. It was for me like learning addition in Math and then jump straight away to rocket science! So this was my first experience about Object Oriented programming. I was using 4 years object oriented programming in Java but I couldn’t understand what was the real reason to use it. For me it was just a necessary evil to learn it as in my mind it was something that I HAD to write in order to get the expected results.
I can give you a simple example. The very basic example that I’ve started with in Java was:
public class Root {
    public static void main(String[] args) {
        System.out.print("Hello World\n");
    }
}
The problem here is that I don’t need all of these and I didn’t even know what the “class” was or what the “public” or what the “static” or what the “void” means… . The only thing that I wanted to do is to have a very first “Hello World” in my screen. So I just copy-paste the class with the unknown public static void main(String[] args) { in order to make it work!!

Hey wait! Are we talking about Java or PHP?

Don’t worry we are getting there…
In PHP the same example, can be easily written like this:
<?php print "Hello World!";
And with this code I can straight away understand that “<?php” is to start php code. Easy to remember and next time I will not have to copy my previous code in order to print something on my screen. It is bad to copy something without knowing and understanding the reason that this is there. What I am trying to say is that it is always better to start USING classes only when you REALLY know what they are doing.

Why OO Programming?

PHP gives us the opportunity to not use Object Oriented Programming if we don’t really need it. This is very cool as Beginners can create a whole website without using any object. So why to use Object Oriented Programming?
It took me 2 years to actually realize the power of Object Oriented Programming! Of course while you are now reading this article you will think that I have a comprehension problem. Although this is not the case! At the very first moment when I started learning why to use Object Oriented Programming, I understood it pretty well. I understood pretty well that your code can be much more extendable and testable and lot of more things like that. However to actually REALIZE the importance of Object Oriented Programming needs time and lot of practice. In the real world (especially at work… world) things are different. In the real world the business only cares for the actual results that our code is rendering. When we are coding the only thing that we have in mind is “How can I get the expected results with the fastest possible way?”. This is the wrong way to think and I will prove it with an example.
So let’s start with a very basic page in PHP. Let’s say that we want to show the user’s first name and last name when he/she firsts login. Also let’s say that there is lot of pressure at the office and this need to be ready… now :) .
Our first attempt is without using objects at all.
<?php
$con = mysqli_connect("example.com","peter","abc123","my_db");

if (mysqli_connect_errno($con)) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '". mysqli_real_escape_string($_GET['user_id'])."'");

$row = mysqli_fetch_array($result)

echo "<div>";
echo $row['first_name'] . " " . $row['last_name'];
echo "</div>";

mysqli_close($con);
?> 
So with the above example our request is done. So as for the request. “I want you to show me the first and last name when the user firsts logged in.” , it is done! Your boss is very proud of your work. You are very proud as this was really easy and it was really fast as well. Moreover as we don’t have a big experience with coding, we are happy that the results are actually showing at the screen.
This is a completely wrong way to think though. Your code isn’t there to be executed only once. This code will be executed now and it will be there in the future (your code lifetime can be 4 months, 1 year… maybe 10 years!). So at one point this code need to change. So your code will never actually be exactly the same for ever. So for this specific example, we can see there is only one situation that the User’s first name and last name will appear. Only if we have the user_id at the URL as a GET parameter. So let’s say that we revisited our code after 1 month. Customer saw that user’s where adding URL’s like http://www.example.com?user_id={random_id} and they where looking the first and last name of other users at the website. Also we realized that we don’t only need to show the first name and last name once but we want to show it everytime (e.g. with a session) when a user is logged in.
One month later you see your own code and you don’t remember what you had done so you start reading again your code line by line.. So as we can see it was fast at the beginning but it is not so fast now that you are searching all your code to check where to change your $_GET[‘user_id’] with $_SESSION[‘user_id’] . Your code is not readable and you are changing your whole code again and again with each request. Some requests can come later like “We want when the user is not logged in to show a button ‘Register’ and redirect him to a registration page.”, “We want to add the email of the user as well so it will be: John Smith (john@smith.com)” , “As this functionality is working well we need to implement it to our back-office as well”… .e.t.c. As you can see lot of small changes can happen but with the above code one thing is for sure. You will always read all of your code to understand what is going on and the tasks will getting more difficult and more difficult. A small example about a messy code that I have in mind is the below:
<?php
$con = mysqli_connect("example.com","peter","abc123","my_db");

if (mysqli_connect_errno($con)) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if (isset($_GET['user_id'])) {
 $result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '". mysqli_real_escape_string($_GET['user_id'])."'");
}elseif (isset($_SESSION['user_id'])) {
 $result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '". mysqli_real_escape_string($_SESSION['user_id'])."'");
}

if (!isset($result)) {
 $row = mysqli_fetch_array($result)

 echo "<div>";
 echo $row['first_name'] . " " . $row['last_name']." (".$row['email'].")";
 echo "</div>";
} else {
 echo "<form action="/register-form.php"><button>Register</button></form>";
}
mysqli_close($con);
?> 
Your code is already a mess. It is difficult to do any change. It is difficult to understand what is going on and you can easily do mistakes.

Objects for the Rescue!

So now that we have a very first impression of our request, let’s re-create our example from scratch!
I will try to explain as less as possible for the object interfaces… e.t.c. as this is not the purpose of this article.
Let’s see our final re-make of our code with OO programming.
//Get User's info by the userID
$user_info = User::getUserInfoById($user_id);

//Render data to the View
$view = new View();
$view->user_info = $user_info;

$view->render('user_details');
As you can see your code is now much more readable (That’s 1). We can now read it and add some automated tests to our Objects as well (That’s 2). Many people may ask where the rest code gone? Where is the database connection, where is the redirection, where is the $user_id is coming from? This doesn’t really matters as it is happening at a separate place of the code. Probably a different file. And this is one more thing that OO Programming is offering to you, you separate your code to different files and you can have a better structure of your code (That’s 3). For example we have different file for Presentation (View), different file for database connection (config) and different file for our business logic (Controller). One more thing that OO Programing is offering is the Don’t Repeat YourSelf (DRYprinciple (That’s 4). And once you have all the good benefits of OO Programming your gift is that your codewill be extendable for the future (That’s 5)
People may thing that objects are bad! They are complex, they are confusing and they are hard to learn. I am sorry people but that’s wrong! Objects are good for anyone! Many people think that Objects are evil and they are trying to make our life harder. Convince yourself that Objects are Angels that trying to save you from long term problems . It will save your time and effort. Objects Oriented programming is like Batman in Gotham City… many people think that he is evil, but he is always there to save you from the bad people (in our case bad coding :) ).
object oriented for the rescue
So let’s have a summary:
1. Your code will be more readable.
2. Your code is testable (for example you can use automated tests like PHPUnit)
3. Your code will have a better structure.
4. You will follow the DRY principle at your code (and this will make you proud)
5. Your code will be extendable for the future.
Now in my opinion few more things that OO can help is:
6. You can get a better quality job if you know OO Programming as business will understand the difference.
7. You can be more proud of yourself when you are coding.
8. You can communicate with other developers in all around the world more easy.
There are plenty of other benefits that OO programing is offering. This article is pointing only few of them.

You convinced me, what is the next step?

If you are really interested about OO Programming in PHP, you can learn more by reading this article . It is a very good start and it has lot of examples.
Once you are done with learning OO Programming, you can start using an MVC PHP Framework for your project. Don’t be afraid to start using them. They are lot of them out there and it doesn’t take a big effort to install them! Here is a list of the most famous ones (starting from the simplest one):
– Codeigniter
– CakePHP
– Yii
– Laravel
– Symfony
– Zend Framework
Want to learn even more? You want to learn the real OO design principles and why everything your boss told you about inheritance might be wrong (and what to do instead)? Head First Design Patterns is the the book that made me realize the power of OO Design Patterns. Why don’t you give a try?
I hope you will enjoy OO Programing as much as I do. Any comments or suggestions are always welcome. Happy coding :)


Sumber

0 komentar:

Posting Komentar