what-is-oop

Learning PHP – Simplifying Object Oriented Programming (OOP)

Software development is a multi faceted activity. While code creation is clearly very crucial, there are many other aspect that often get overlooked. One such aspect is programming paradigm. Simply put, how the application is structured from a programming standpoint.  While learning to code, it’s also important to notice how things align in the bigger picture.

Code doesn’t only need to work, it also needs to be planned and organised in such a way that, other humans are able to easily read it. Making alterations and adding new features should also be simple and straightforward. Enabling all of these features needs careful planning and proper understanding of different programming paradigms.

There are two broad ways of programming in PHP
1. Procedural Programming
2. Object Oriented Programming (OOP)

1. Procedural Programming : Software designed around the logical flow of the application. Here, the programmer would simply think of how activities would flow from the user to the system and output. Then accordingly write code to receive the input, process it, and then display the output. Given it’s intuitive nature, it is used extensively in most early learning examples of PHP code. Mostly developers will find themselves copy pasting “chunks” of code from one part of the application to the other. The code tends to get lengthy in most cases. While it is a little intuitive, it isn’t a good way to design applications. Making changes, adding features etc can be a pain even in the smallest of cases.

2. Object Oriented Programming (OOP) : Software design focused on structuring the overall application into groups of interrelated data and associated actions . These groups are known as objects. I like to think of it, as creating a hypothetical RPG (Role Playing Game). Here your entire application now has “characters” with special “properties” and certain “capabilities”. I might be stretching it a little, but these kinda examples helped me understand the concept better. Most OOP tutorials go wrong when trying to give real world examples to explain “objects”, it soon loses relevance and the reader remains puzzled wondering how to apply this at the code level.

Almost always, PHP learners would first be introduced to procedural programing. If they have little or no prior programing knowledge, they are most likely to get habituated to this style of coding. Which in turn makes it even tougher to transition to OOP. Hence, it’s always advisable to touch upon the concept of OOP as early as possible.

My experience with most OOP tutorials is that “real world” examples only add to the confusion. Hence I’m trying a different approach.

Let’s use an actual coding scenario and explore how one would go about making an application.

E-Commerce Example

Let’s say we are building an E-Commerce website. A common list of pages would be as follows.

  1. Home Page: List of best selling products, latest offers etc
  2. Category Page: List of products from a certain category
  3. Product Page: Details about a certain product
  4. Login Page: Simple login form
  5. User Page: List of recently purchased items, details of products in transit etc
  6. Payment and checkout page(s): Details about shipping,payments etc

and so on and so forth.

The procedural way

A procedural programmer is likely to make a separate file for each of the pages mentioned above.

Here’s a (very rough) sample of what the home page would look like

And so on an so forth.

It’s likely that the homepage code would be replicated to create pages like “Category.php”, “Product.php” etc. The only thing left to do is change the SQL script and maybe the html a bit and viola! a working set of pages prepared in no time.

This sounds good because

  1. Its pretty intuitive hence easy to understand
  2. Saved a lot of time
  3. Works pretty well

But what if you needed to alter the database a little.  Let’s say you have product name and code stored in the same column “Product”.  Now you need to divide this column into two separate columns “Name” and “Code”. For the new structure to work you would have to go back and change every MySQL query mentioning the column “Product”.

Now it doesn’t sound so good because

  1. Not intuitive anymore: Even the simplest change now seems like a complex affair.
  2. Time Consuming: Though it’s just one column that’s added, it also implies tens and maybe hundreds of alterations to code.
  3. Might not work: It’s humanly impossible to remember every query and line of code in your application. Missing out somewhere means the application would break on that page.

While procedural makes sense for very small simple examples, it falls flat on larger projects like the one mentioned above.

The OOP way

One of the most common mistakes people make when understanding Object Oriented Programming is thinking it’s simply stuffing procedural code into “Classes” or “Objects” that can be reused. Object oriented programing is not about organising logic, it’s more about organising data. If this sounds complicated, don’t worry, things should get clear once we jump into the example.

Object Oriented Programming would not look at the pages mentioned above. Instead it would look at the different entities the E-Commerce Website would comprise of. A few examples would include

  • product
  • user
  • shopingCart
  • offers

Each of these entities are examples of objects. Each object would have certain properties ( better known as attributes) and capabilities ( known as methods). Methods are mostly used to alter the values of attributes but can also perform other activities.

For example, “Product” will have an attribute like “Price” and a method like “DiscountPrice(%)” or “setPrice()”. DiscountPrice(20%) could then reduce the price by 20%. Here are a few more examples to make things clearer.

objectExamplesAs mentioned earlier, methods can do things other than manipulate attributes. Like in the case of “sendPurchaseConfirmation()” where it would simply send a mail to whatever is set at “email” for a user.

Once we have identified the objects, we would have to define them in our application. This is done through classes. Classes are simply “templates” of objects. You can think of them as empty skeletons with no data.

Thus the “Product” class would not have any price or name set. However it will be aware that it needs to hold a value for price and another for name. It would also be aware that it can discount this price.

When a class is “Instantiated”, an object will be created. This object will hold the real values of price and name.

Here’s how one would define the product class

Thus, in this case if you planned on changing the database a bit, you would only have to change your code once – Here.

Hope the concept of OOP is now making more sense.

So we now have these classes, let’s see how to use them as objects.

A new object can be made in the following way

This will work only if the code for the “product” class in within scope (Part of the same file or included before this line).

Constructors

You probably noticed a method “__construct”. This is a special kind of method known as a constructor. It executes when you create a new object but is not mandatory.

The line above will create a new object whether or not you have a constructor. In this case it would set the name, price, category and stock based on the variables $name, $price, $category and $stockQuantity. If the constructor was not added, it would just create an empty object, you could then set the values individually.

Return

You may have also noticed the term “return” in the above example, this simply means “output” the value from the method / attribute. For example

would set the value of $stockCount to whatever value was obtained from the refreshStockQuantity() code. If the last line of refreshStockQuantity() was

the value of $stockCount would always be ‘123’;

More about Objects

Classes can have subclasses – A subclass will be a new class that “inherits” attributes and methods from the parent class and can have additional attributes and methods specific to itself. For example “product” might have “electronicProduct” as a subclass. Just like product, electronicProduct would also have name,category,price and stock. But additionally it would also have power rating.
Subclasses are defined in the following way

Objects can interact with each other – An object can create another object from within one of it’s methods. This internal object can have it’s attributes and methods accessed and manipulated based on whether they are private, public or protected.

  • Private : Accessible only by the internal object
  • Public : Accessible across the application (All objects)
  • protected : Accessible only to other objects of the same kind

Attributes and methods can be set as static variables if needed – Static variables hold it’s value for all instances of an object. So let’s say I have created an object A and set it’s attribute to 7. After this, if I were to create another object B it’s attribute would be set to 7 by default. This is because the value “7” from the previous object “stuck around” till the next instance (Object B).

As they are not specific to any instance “$this” would not be available inside a static method. Also static attributes and methods don’t need a new object to be instantiated before it were used. We come simply access them in the following way.

There is no need for “$product = new product;” to be called before this line as $stockQuantity was mentioned as static;

So coming back to our “home page example”, with OOP, the page would look somewhat like this

Please note, the code examples here, were a very rough version of what the real code would look like. In a real world scenario the code would be a bit more complex with use of classes and subclasses.

While you might now be familiar with OOP as a concept, keep in mind that this post was really just “scratching the surface”. There’s a lot more to Object Oriented Programming, which I have deliberately omitted here for the sake of simplicity. Feel free to dig  around and write back any concept you find tough to grasp.

Related Posts