r/PHPhelp • • Oct 05 '16

PHP OOP. When and Why?

Ok, so I just have a question regarding object oriented programming that I have been pondering for the better part of the last few days.

I'm currently working on a personal project that essentially involves reverse engineering a website to create essentially a clone that I can use for a private server of a game. I know it sounds incredibly strange but it's a long story as to why I'm doing it and it basically boils down to me being bored, and now I intend to finish it as a challenge in my free time. Anyhow, basically I know how every aspect of the site functions, which pages call which and how (it uses AngularJS and handles most I/O using JSON). So, piece by piece I've been rebuilding the back end of each aspect of the site to function how they do on the real thing (login, registration, user settings, etc) and I actually have probably 75% of the site functional.

This is where the question comes into play. I've designed each back end file separately and procedurally, however, reading a documentation online for various aspects of PHP has shown me that a vast majority of projects are done in the OOP style and not procedurally. Now, I'm totally new to OOP (I'm in my 3rd of year of a CS degree) but a ton of the examples online do not make it clear as to why OOP is considered a better practice.

All I see are posts discussing about how you should use objects in PHP when you are dealing with multiple sets of similar data. That's fine and all, but now I don't see when that really occurs on a webpage. If you are handling user data, you are dealing with a single user accessing the page, so why create an object to hold and manage that data when you are dealing with one user? Why not simply collect that data into a set of variables and manipulate it how you wish in a procedural fashion, which to me seems much easier than having a separate class file, including the class file, creating and initializing the object with the data and then accessing the object to manipulate it.

I do use a class in my project which acts as a bit of a wrapper for PDO and does some error handling as well as some custom query stuff to simplify querying the database. I actually don't really see why this should be a class either. Why should my custom query function be in a class? I have a globally included file that is required by every document in my project, which sets some variables used site-wide from a configuration file, such as the database server information. So why not in that same globally included file do I not just create a PDO connection and define my query function, which can then be used by anything including that file.

Example

function connectDB($host, $name, $pass, $db)
    //Connect to the database and handle exceptions

function queryDB($statement, ...$params)
    //Query the database with the provided statement and parameters to be bound to the statement and handle exceptions

So why should I encapsulate those into a class when I could just have them in global.php, included across my project and call them whenever I want. As I have it now, those are in class which means in global.php I have to create and object and then whenever I want to use those functions I have to write $object->connectDB(...), instead of just connectDB(...), which seems so pointless to me when, yes those to functions are related in that they both involve the database, but other than that they do not interact.

An example of one aspect of my project's functionality: The user clicks the 'News' tab, Angular sees the URL is pointing to the news page so it loads /system/news.php which pulls a list of articles from the database, loops through them and generates HTML for them that is displayed in the page by Angular. In what way would something like this be better as an object? Sure I could create a news object that stores each part of the article (title, body, date, author, etc) but then I'm just outputting them after anyways so I don't see the point. I could also create an object that holds each news articles data and has methods for generating and outputting HTML, which again seems like I'm needlessly creating a class and moving my code into another file, to basically call it from one other file, since that code is only ever used on the news page.

At the end of the day, my question is, why do people insist on using OOP, which splits up your code into classes which are driven by a main index page, when you can simple write each separate piece of functionality in it's own file and call it when necessary?

7 Upvotes

6 comments sorted by

3

u/colshrapnel Oct 05 '16

The very first thing you have to understand about OOP and - especially - its use: unlike other concepts related to web-programming and PHP, object oriented programming and design is not a thing you can get grasp of in a matter of seconds. Or a matter of a couple comments on Reddit. It's a thing that will take you years to comprehend.

To answer the bottom line question. You are absolutely right: to some degree there is no point in using OOP. As long as our site is just a set of simple one-action pages, it's easier to keep it procedural. You will start feeling the need for objects only when you site become considerably bigger, each page doing hundreds of actions - checking access rights, caching, responding in different formats, logging, debugging, abd thousands of other actions.

1

u/judgej2 Oct 05 '16

It's a thing that will take you years to comprehend.

So the answer to when and why, is now and because you need to get the experience under your belt before being able to apply it in a proper project.

2

u/liquid_at Oct 05 '16

The advantage of OOP is that you can use the same classes for different projects. By extending classes and using existing ones.

When you create a REST-basted application, you basically create an interface between the webserver and clients to communicate data over. When doing OOP, you basically do the same for variables and functions. That allows you and others to re-use your code a lot easier with less effort.

As I see it, it's mainly a different way to structure your code. By compartmentalising it, you allow each individual part to be a closed system that can be replaced and reused as you please. You just need to weigh your need for shorter code against your need for reusing code. Whatever is more important to you, will decide what you prefer.

1

u/judgej2 Oct 05 '16

Your last part to your question seems to be mixing up some concepts. Using OOP is not related to having a single entry point to an application. Using a single entry point (index.php) means you can separate the paths to resources and actions from the underlying functionality that returns the resource. Going through that one point means the path can be routed to the appropriate function, and various checks can be done on the way - checking the resource exists, that you are allowed to access it, etc.

If you don't have one entry point with routing for paths, then every single URL path must have its own PHP script to render it. That can get very unmanageable once the application grows large, since you end up with duplicated code all over the place (you have already pointed out that your scripts simply have to include the right files - but really, thinking that way went out with the dark ages of the early noughties).

1

u/headzoo Oct 05 '16

You should be asking the question, "Why is global state bad?" You think procedural programming is easier because you're using bad programming practices.

1

u/cyrusol Oct 10 '16

First off, including (requiring) other PHP files is a thing of the past. Composer's autoloader implements the PSR-0 and PSR-4 standards. Namespaces and use declarations make our lives so much easier.

Now about OOP:

You have asked to why not just have a few variables describing a user: Because in the long run a few variables will become many. Users might become more than just personal identifications. Maybe there will be a premium subscription? Orders? Extensive profiles with visibility settings as detailed as in Facebook? We can't know the future. To some extent this isn't true for your own personal projects but it definitely is true when you start to work for clients. I would like to answer your questions with this questions: Why having to bother with 2 to N variables when I can wrap all user-related business logic in one variable (holding the user object)?

When you count apples in a basket and there are 4 you can immediately see it. That remains true for up to around 7 apples for most people. Some can still easily identify 9 or even 11 apples without having to actually count them. But if there were 30 apples you'd have to count them. It works the same way with available programming states in the current context, or with numbers of lines in a function. When writing code (or reading and trying to understand code) you have to constantly keep everything that is available in mind to not accidentally break anything. Abstraction relieves you of this mind-boggling task. It is far easier to deal with 6 baskets with 5 apples each than to deal with 1 basket with 30 apples.

As long as you don't think you need to simplify your code that's fine. But at some point you will see the need for it. For example when dealing with money payments (of course use a 3rd party payment provider such as Paypal or one of its many competitors) you have to constantly check status codes und handle errors, it makes for about 70% to 90% of the whole logic. For a real-world project I'm making use of extreme abstraction but I still have methods with 100 lines which is like 90 too many and it makes me ashamed of myself.

Then there is code duplication. I believe you have many duplicate code. I cannot know as long as you don't share a few excerpts of your code but you don't have to.

There are the [SOLID](https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)) principles. They pretty much dictate how good object-oriented design has to look like. You might find more reasons for OOP in the reasons for those principles.

In the end OOP should simplify your code, make it maintainable, give more possibilites for abstraction than just flat and higher-order functions and should allow for a workflow that supports business requirements, i.e. adding new features fast without damaging existing ones.