PHP Procedural vs Object Oriented

Was just reading through a book, “PHP 5 Advanced” by Lary Ullman. He goes over OOP style PHP. I see it used often in CMS’s such as WordPress, but I don’t really know what the benefit is to OOP coding over Procedural coding. Can anyone help explain the pro’s and con’s of each and share your personal opinions on each?

Procedural programming is for amateurs, OOP on the other hand is what it takes for professional programming. In a perfect script, everything is an object.

OOP offers encapsulation, inheritance, polymorphism and composition, it helps you build much more extendable, reusable, maintainable, and organized application. The advantages are more evident in larger programs, which are pretty much impossible to work on with procedural style, especially when teamwork is required.

For newbies, I’d recommend you to work on a project and learn step by step on why OOP will help you create better software. As your application grows in size and complexity, you will realize how it’s difficult or impossible to extend your application further if its written in procedural style. At this point, you won’t ever want to code in procedural php any longer.

Broadly speaking, the difference is that in procedural programming you create functions (procedures) which act on data structures. With OOP, you’re creating objects which encapsulate both data and the methods which act on it.

The idea behind OOP was to make programs easier to write and maintain by allowing problems to be modeled in terms of objects which represent the entities or concepts that the application deals with. One of the classic examples is that of a banking application, where you might have objects that represent customers, accounts, balance transfers, and loans etc.

In my opinion, procedural programming is still useful for writing small, simple scripts… you might use it when writing a utility script to periodically clean up old log files or something like that. Using objects in a scenario like this would be overkill.

As soon as you start getting more complex with your requirements, and there’s the possibility that the program might have to accomodate changes over time, then OOP is the way to go. That said, be aware that just grouping together your functions into classes doesn’t make your code OO… good OO design is something that needs to be learned and practiced.

Thanks for the info guys. Maybe v2 of the CMS I’m coding will convert to OOP. Not sure though as seems like procedural is more commonly used still and the CMS will be open source for users to develop their own plugins/modifications.

I just started the chapters on OOP, but it kinda seems like an object is similar to a function, which contains other functions.

Well, first off, let’s be clear that OOP is a technique for programming. Anything you can do in OOP, you can also do in procedural. When we say a language is object oriented, that means it provides mechanisms that makes it convenient to use the object oriented style. For example, we could write object oriented programs in C, but it would be unnecessarily hard because that language doesn’t support object oriented techniques.

Now to more directly answer your question: In procedural, the focus is on the processing – the algorithm needed to perform the desired computation. Whereas in OOP, the focus is on data organization and abstraction. It tries to make us think of our program as interacting concepts rather than as a bunch of data with functions twiddling their bits. The goal is to write programs that scale better and are more adaptable to change.

Wow…I’d certainly disagree to statement #1, and with the end of statement #2.

This is from a lecture on java, it’s a pretty good explanation on OOP and the differences with procedural programming. http://www.ctp.bilkent.edu.tr/~russell/java/LectureNotes/1_OOConcepts.htm

I’ve written in both, and have seen true cludge and spaghetti code from both. The benefit I’ve personally seen from procedural is it tends to force people to think a little before writing. What I’ve seen in OOP far too many times is people trying to throw an override method which calls another override, which calls another override, etc. when it would make more sense to take a moment to re-engineer the methods.

The biggest difference to me is the approach - procedural focuses more on functionality (ideally each procedure focuses on one piece of functionality), and OOP is focused on considering everything as an object.

Edit:

Jeff spelled it out better than me

Hi,

I know this doesn’t really contribute much to the discussion at hand, but isn’t WordPress’s code base largely procedural?
Or are you talking about various WP plugins?

I find the direct opposite to be true. In my experience, procedural programming tends to have almost no thought behind it - just make the functionality and be done with it. This leads to systems that are generally very messy and hard to extend in the future.

On the other hand, OOP (done well) is all about thinking about how your application may need to adapt over time - good OO systems have very focused objects that do one thing well - a good system will have nice clean interfaces that makes expansions and adjustments really easy. If I’m writing a reporting system for example, I’ll tend to focus on the interfaces for my report objects first - I’d then make a bunch of writer objects that take the report interface and output the report in whatever format I want. This would mean I could create new reports easily, and combined with separate report writers, I could output to excel, json, csv etc etc, and every element would stay compatible with every other element.

OOP done well leads to nice clear designs that are easy to work with an expand upon. Unfortunately, there is a lot of php code out there that uses classes, but is not actually object oriented, and it seems from what you’ve said, that this is the kind of code you have experienced in the past.

I’m not sure about all their code but I know to access a lot of variables they use OOP style variables. WP is just sloppy in my personal opinion.

I use SmartyPHP template system for my CMS and it uses OOP. $smarty->assign(‘variable_name’, ‘variable value’);

Quick n dirty list of benefits of object oriented design. The main bullet point of OOP is less code (if done right). From there we can get these much more important points:

  1. Readability - You may not think so since your new to it, but I kill over being handed a large procedural project management wants modified.
  2. Ease of changes - Make changes in once place rather than many
  3. Stability - Less chance for slightly different code being produced in multiple places. This is a HUGE deal with bigger projects. HUGE. Did I mention HUGE? A bigger PHP project without strict OO concepts is the first step toward failure.

Beginner Example:

Imagine writing an application that has to make a database connection multiple times (across multiple scripts). Each time you write it out you have at least 2-3 lines dedicated just to the connection. If you ever change credentials or location of the database, you’d have to come back to each page and make the change. A proper OOP setup would mean you only initiate a new DB object that you created which handles your connection for you. Now you or another developer only needs to make a change in one location rather than 10.

While this is a good example showing how to structure things right I don’t see it as having anything to do with procedural vs object-oriented. In procedural you simply create the db connection once and store it in a global variable to be accessed by all functions and when credentials change they are still in one place. Or, you create a single function for fetching the db connection and use it everywhere. Or, you store the credentials in a single config file, which can be done with procedural code as well. So I think a better “Begginer Example” would be better :).

But yes, I’ve seen procedural code where the same db credentials were scattered around 10 different files - this was a pretty large online shop that I inherited to work on and the end result was that I decided to write it again from scratch :).

Correct. In fact, that is a good relevant point. WP’s core code is a bit of a mess. While using objects doesn’t guarantee your code is neat and well organised, it certainly does help. What I love with objects is how relevant functions are grouped together and relationship between different functions is better described. Having written procedural for years, I relatively recently moved to objects and it’s like new life has been breathed into my code.

I use procedural functions for any site-spefiic niche functions but everything else is done with class/objects.

Creating a global variable would be absolutely horrible. Globals are evil.

I’m following along from the sidelines here and just wondered, given that globals are evil, what would be your preferred method of making a database connection multiple times (across multiple scripts) using procedural code?

This is not the point. I just pointed out how they could be used to keep database credentials in a centralized place using procedural programming.

Back in the days when I used procedural programming only I used a global variable and it worked well. But I produced a lot of spaghetti code so I’m not sure if this was the best way.

Maybe a singleton-ish function like getDbConnection() would be better. I don’t know if passing around a database handle would be feasible in procedural.

But anyway, this database connection problem didn’t really exist back in the old PHP days because the old mysql functions didn’t require the connection handle so I could simply connect at the beginning of the script and call mysql_query() in any scope without worrying about passing the connection if I used only one database. That was pure genius in its simplicity! :smiley:

Well I don’t write procedural code, and haven’t for a long time… probably about 3-4 years by now.

My code nowadays uses namespaces in php, and all my autoloading is done based on namespaces too, so I don’t need require/include statements all over the place either…

I guess to do this in a procedural way, I’d probably have some kind of dbConnect() function, that would take a constant as a parameter… The constant would point to some config file (like a yaml or xml file) that would contain the database connection details. The script would then create the database connection based on those details.

So for example, if I wanted to connect to two different databases, I could do $connectionA = dbConnect(DATABASE_A);, and for the other I could do $connectionB = dbConnect(DATABASE_B);

If I needed to change the password settings or whatever, I’d change it in the mapping file. There’d be a direct connection between a parameter in the mapping file and the constant value (so it’d be like: DATABASE_B = ‘report_database’ and then in the yaml file or whatever, there’d be a ‘report_database’ key).

Does that make sense?

I’d probably do something like that…

The only thing you are really left with to mind is to wrap it in a function that maintains the static state internally.


/**
* @return Db
*/
function getDb(){
	static $db;
	if( isset($db) ){
		return $db;
	}

	$db = new Db();
	return $db;
}

Two of the only real benefits I can think of are

1 . That is the state is sealed, a global variables very basic existance is too exposed.
eg.


class Db{
	function getUsers(){


	}
}


$db = new Db();
function a(){	
	global $db;
	$db->getUsers();
	$db = null;
}


function b(){
    global $db;
    $db->getUsers(); //fatal where has the db gone in the call chain?
}


a();
b();

Whereas


class Db{
    function getUsers(){


    }
}

function getDb(){
    static $db;
    if( isset($db) ){
        return $db;
    }

    $db = new Db();
    return $db;
}


function a(){
    $db = getDb();
    $db->getUsers();
    $db = null;
}


function b(){
    $db = getDb();
    $db->getUsers(); //nullification of object can only happen in getDb()
}


a();
b();

  1. If logic is required at point of request such as for debugging it can be easily added or a break point can be set.

eg.


function getDb(){
    file_put_contents( 'getDbLog.txt', print_r(debug_backtrace(), true ), FILE_APPEND );
    static $db;
    if( isset($db) ){
        return $db;
    }

    $db = new Db();
    return $db;
}


.

Your first example is what I was thinking here (except getDb() would accept a parameter which could be used to determine which db connection to return) - the only thing is, I wasn’t sure whether you could use a static variable outside of a class scope - it’s possible to do that just in a function then is it?

I imagine that would be a function – get_db_connection or whatever – that you could call from some local scope when you need it. If you think get_db_connection might be called multiple times, then you could use the static keyword to “cache” the db link and return the same value each time.

Of course, the even better option would be the dependency injection / front controller style. (Remember that OOP is a technique, and we can still use that technique even if we don’t use classes.)

<?php

function app($request)
{
    // connect to database
    $db = new PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD');

    // route and do action
    if ($request == '/hello') {
        hello_action($db);
    }
}

function hello_action($db)
{
    echo 'Hello, World!';
}

app('/hello');

That’s a great example of how globals can be dangerous. Any line from anywhere in the program could clobber or otherwise alter a global variable, and there’s no easy way to trace where that clobbering happened. So you end up with code that just doesn’t work for some inexplicable reason.