OOP PHP Sucks!

Update: Before you bash my head in, let me re-phrase the title… ehem… Today’s misuse of OOP sucks as much as misuse of procedural style.

After considering how the web has evolved, I’ve noticed that is not what you use to code, but how you code it that matters more. Yes, what you use still matters, but how you do it matters more. After trying to work on a project using Zend2, I gave up on it when I noticed the ridiculousness of just rendering a page with some dynamic data on it. Autoloading unnecessary libraries, adding layers of abstraction from propel which really all it does is use unnecessary clock cycles to do the same thing that writing your SQL inside a string, building objects that use something like 5% of its functions, “ingest” template files to create some sort of rendering, adding smarty templatizing on top of it that needs to convert to php tags anyway, and finally, the end result.

For real? We NEED to do all that to just render some dynamic page? Wow! We have come a long way in abstracting the simplest solutions into difficult to understand spaghetti code. I’ll explain what I mean by all this.

Let’s look at what actually happens when a web page gets rendered for end users… after all, that’s typically the medium that end users get to interact with in order to have productive or entertaining lives.

It’s a long trip. Hope you brought a book along for the ride.

– Request gets sent to a server via URL inputted by end user typically via the address bar.
– That url gets to travel to DNS servers that send the request to servers identified by IP addresses.
– The server is hit, the server then access its first landing point (htaccess and folder structures) and makes a smart decision in order to try to build some sort of a response to send back.
– At this point, the server will either send you back a message about how it can’t find a file requested, or continue to try to render something to send back.
– Let’s say some default index.html was found without complicating things too much. And let’s say that this file contains basic html, and hopefully somewhat valid html code that gets served to be sent back as data packets back to the original requester.
– The html code comes back to the browser, gets interpreted by the browser, and the browser does its thing to render out the HTML, style with some css code, and run its internal JS engine to see if it has something to do on the client side.

This is where things can get complicated, but why? We don’t have to complicate things. Let’s keep in mind that the final response is simply a long line of characters. There’s absolutely nothing “object oriented” about it. The browser simply takes what it receives and tries to do its job. It’s that simple.

Yes, some JS gets interpreted as objects by the JS engine within the browser, but that’s not for this discussion. Let’s focus on why PHP shouldn’t be OOP.

Back to the server… Here’s what the browser wants:

< html code >
< script code >
< style code >
< html code >
< html code >
< more html code >
< maybe even more script code >

Done. The browser interprets what it gets… or tries to… and renders stuff on the screen. The browser is your application layer.

I cringe every time I hear web developers saying that they’re building an application… You’re nor building squat. Your job is to create browser readable code. That’s it. Just because you’ve overcomplicated your code so much that only you can understand it half the time does not make you an application developer. Creating a browser… now that’s application development. Until that point, you’re just creating a string of characters.

So, then, webpages started to evolve to create dynamic content… So whenever you land on the root of a site, you’re really hitting a script file… something like index.php. Somewhere on the server, in a configuration file, we’ve created the logic to say that the initial point, the entry point should be index.php… we call this the Directory Index.

This file can simply contain pure HTML code just like your *.html files. But… you can do something magical on them. You can render different content. PHP (as well as VB Script used to do), can make this happen. By using the php tags () respectively, you’ve just told the php engine that there’s some code in between. So… PHP, do your thing. Look between these tags and do some work.

I keep hearing from so many new aged developers about keeping your code separated… something about code separation makes things cleaner. I couldn’t agree more… when you’re talking about keeping your styles and JS separate, that’s a great idea. When you’re talking about adding PHP tags in your pages, why are we so scared? the code is completely separated. There’s HTML and then there’s dynamic code inside that HTML that makes sense to have there. The page becomes a template. You don’t need to have template files nested 10 directories deep. The php file itself becomes the template.

I’ve actually heard this argument before… “But php tags look so ugly… so I use smarty tags”. O_O … Are you an idiot? They look ugly? So that’s why you have to add a layer of abstraction on top of it? Adding smarty is not so smarty, is it?… That layer of abstraction just made your code slower because the PHP engine has to now convert ALL of the curly brackets on the page to “ugly” php tags… You know what? If php tags are ugly, then smarty tags are stupid. If that’s the case, I’d rather be ugly than stupid.

It feels like abstraction has gotten out of hand where we now pull HTML templates inside some private function inside a file nested another 10 directories deep.

This mentality of super abstraction is what I have a big issue with when it comes to development for the web. It’s typically engineers who consider themselves super smart coming from the world of Java or C++ who somehow believe that coding on the web is the same thing as console, or application development. It’s not the same thing.

Let me explain so someone as smart as you can understand. Java development doesn’t have a browser for which you need to write a string. It doesn’t have multiple languages to handle, such as HTML, JS and CSS. It’s one code… assembly. And of course, to make it easy, there have been compilers built that can convert all of your nicely written OOP code in code that the machine understands. It gets compiled, and your code is typically living within the Java engine that you downloaded and installed (not a browser, it’s an engine with which the user never directly interacts). It stays in RAM. HTML code doesn’t stay in RAM. It gets put on a disk (browser cache). The CSS, same thing. The JS, same thing. All those pretty objects that you took all that time to build, are gone! Not in memory. Not on the disk. It’s all gone. Oh, you want to access them? Well, then we have to hit a database on a server somewhere far away from your home in order to re-build whatever you’re seeking. Get it? It’s not the same thing as app development.

If you work with PHP, you’re not building any application. You’re building code that’s to be interpreted by the PHP engine on the server in order to deliver a string of characters back to someone using a browser.

Applications, on the other hand, get installed on consoles, and PCs, and hand held devices. Upon starting the application, a whole bunch of stuff gets loaded in memory, and then the program itself uses those bits from memory. And all that stays in memory while the program is active. Only when you chose to quit the application does the application unload itself from memory. All those “object pointers” for functions and variables get cleared out.

In the end, I suppose some will never understand the difference between application and web page no matter how much you try to explain to them. Or, someone will come along claiming that they’re working on a huge website where OOP is saving their life, or some brainiac engineer claims that they don’t see how they could have built their “web app” without OOP. Obviously they’re not intelligent enough to realize that before “web oop” ALL websites were done without OOP, and they did just fine, because they built them well. It was how they coded them that mattered, not what techniques they used.

This was my rant. Thank you for listening / reading.

Update: After careful consideration, and many of your comments, I’ve come to the conclusion that it’s not OOP that I hate. I think it’s the misuse of it. Writing your models in a way that you have to load all of them for something simple… writing your SQL queries so you have to loop through database requests because you must use ORMs… instead of just writing a query that’s more complex, but increases performance 10 fold… Oh, and what’s wrong with SQL itself? It’s an awesome language to know.

I believe that it’s the way coders have been writing code that’s more of an issue for me than the actual style. PHP is not Ruby. Not everything is an object… especially when it comes to rendering things in HTML.

I’ve been using Code Igniter for my latest two projects and it’s not as painful anymore. I don’t like how it routes things as Apache is much more performant when it comes time to handle routes via Rewrite Module.

I also miss the idea of finding a page in the root (about.php) for an “/about.html” request. However… if you check your routes, it should be no problem to navigate through controllers then views (partials too). Still… looking through three or four different files to find what I’m seeking, is more work than I’d like to do… one file… off the root… about.php. Done. I suppose I can do that if I alter my htaccess file, but then… why am I using CI in the first place?

Anyway… I’ll continue to use a mix of procedural and OOP code as I’ve been doing more of lately. (Using 3rd party libraries has become a bit easier).

Once again, thanks for listening. I hope this can help other “non-believers” to understand that we need to understand our needs before we write any code.

I wonder if facebook or google uses any OOP development on the back end in their websites… er… web apps.

  • This rant makes total sense to anyone not familiar with MVC. Once you start using the pattern and appreciate it, you get to see *whey(where and why) OOP and even smarty fit in.

    • Simon

      Separation of concerns is something George has either not heard of, or not grasped. He goes as far as complecting server responses with DOM element IDs. So this should come as no surprise.

    • George

      I’m familiar with MVC, I just don’t see the benefits of it in a web type environment. It just complicates things. Web pages are single applications, starting with the request, the headers, a bunch of HTML which is really just a really long string, and that completes the response. Why do we complicate things with MVC, which is great for Java apps, VB / VC++ Desktop apps, iOs / Droid apps, when all we need is too keep in mind what’s being done here… and that is… the rendering of one html document. I remember the old days when a dynamic language was used to make a static page dynamic, not define an entire back-end architecture.

      The only thing OOP has done for PHP was to make it a more well structured spaghetti code. Have you not looked at the frameworks out there? They took something very simple and complicated the crap out of it. Nowadays it’s all about models and controllers, and although I agree that there has to be some structure with coding, it’s nothing you can’t accomplish with basic functions, procedural style even. Need access to global variables? PHP already does that for you for the purpose of using existing variables in your little procedural functions. Is that a bad thing? How so? It’s a practice that’s been used over and over, and even cherished by WordPress itself, the most popular blogging CMS out there. Functions are there to help aide your coding, not make it more complex.

      We keep making things so complex for the false idea that one day everything will be simple if everyone uses a complex system. If oop would have truly solved anything, everyone would be using it. Unfortunately, google doesn’t lie when it spews out results on why OOP PHP sucks.

      Cheers, mate!

      • The spaghetti code is what gives PHP the infamous rap, with valid reasons. I wouldn’t want to maintain code(even my own) as haphazardly written as that, some that I have written in the past, regrettably. I also find it defeatist that you term your code spaghetti, a veritable vice in scripting circles 🙂

        I’m not a big fan of PHP frameworks for several pragmatic reasons, I prefer a custom MVC framework of which I use Smarty. The HTML rendering business is remotely my domain and therefore should be easily modified without affecting other bits of munge and logic. I don’t see it as complex, the same benefits you see in Java and Python are the same ones you seek in OOP PHP. You wrap your typical functions logically into classes (and namespaces where necessary) and the output is still the same. By putting your functions as methods into classes, you mentally create a structure that models your entire web app. With this you’ll get the benefit of reusing methods all over and return data to different templates. It also makes it easy to trace source of bugs and fix in one place. Any medium/large-scale system in PHP is therefore better-off in OOP. It promotes reusability, maintainability, and sanity O_o. I think you approach dynamic content delivery with PHP in a far simplistic way to appreciate the concept in all its goodness. If you are building a sustainable application to run on a browser, and has to be dynamic, presentation should be the least of your focus. Because it’s the easiest bit to maintain and alter.

        Cheers!

        • George

          Why write classes and create objects when functions do the same exact thing. Well structured procedural style of coding will always win against the modern day architectures that I’ve had to work with in the past. Object development somehow seems to promote lazy coding, which creates layers and layers of unnecessary abstraction.

          As far as using a custom MVC pattern, I agree to a certain extent. I’ve started doing something similar, but MVC doesn’t have to do anything with OOP. My MVC structure is still implemented via procedural functions.

          • toach

            “Object development somehow seems to promote lazy coding”

            Explain please.

          • George

            There’s this misconception that writing classes promotes reusable code, as if writing functions doesn’t. I’ve heard so many times OOP devs mentioning how they can extend classes instead of having to duplicate functionality.

            In reality, all of the duplicate code that I’ve ever seen was not truly duplicate. There were always parameters and differences. One example: The user information that the end users see vs what the admin sees is never the same. The admin has access to emails, user ids, sometimes passwords, etc. So, technically, to render out user information for admins is different than to render out information for admins. The data may be similar… but not the same. Therefore, it’s two different functions.

            So then… OOP devs start building abstraction classes and extend classes in order to solve the misconception of repetition once again. In reality (from my experience again), this becomes a nested nightmare of abstraction.

            Basically, to explain myself, I would have to say that trying to make things easier (laziness) is becoming the standard, and the next person that comes in, not knowing what they’re looking at, gets confused really easy without the proper training.

            Another thing I’ve noticed is the idea that if you write OO code, the code writes itself, and no more need for documentation, flow charts, system design, architecture maps, and the likes. Again, trying to be lazy, and not do the hard work, in order to pretend that OO code is the savior of all.

            I’ve built many, many applications in pure procedural code and I go back from year to year to make changes to, and I tell you… I’ve kept abstraction away from that code from the beginning, and I’m thankful for it. It doesn’t take me hours to navigate through classes, extended classes, abstract classes. I just look at the original php file, it has a function… I do a search for that function and done!

            That’s not laziness, it’s common sense. Simplicity. Have you ever worked on a Zend project? Have you had to go back to it years later only to lose yourself in the nested hierarchy of classes? I have. Countless times.

            I hope I helped explain my point.

          • toach

            For discussion, I have added some responses to your previous comments.

            “There’s this misconception that writing classes promotes reusable code, as if writing functions doesn’t.”

            Code reuse has nothing to do with OOPS vs procedural programming but rather good development practices.

            “In reality, all of the duplicate code that I’ve ever seen was not truly duplicate. There were always parameters and differences.”

            This, again, has nothing to do with OOPs and more to do with development practices.

            “So then… OOP devs start building abstraction classes and extend classes in order to solve the misconception of repetition once again.”

            For me personally, when dealing with repetition/duplication DRY is best but I try to stick to the rule of three.

            “In reality (from my experience again), this becomes a nested nightmare of abstraction.”

            Again, not addressing OOPs but bad design patterns.

            “I would have to say that trying to make things easier (laziness) is becoming the standard”

            Work smarter, not harder.

            “Life is really simple, but we insist on making it difficult”

            – Confucius

            “and the next person that comes in, not knowing what they’re looking at, gets confused really easy without the proper training.”

            Yeah, a person working as a professional developer should have proper training. If you don’t understand OOPs you probably aren’t going to get a job where it’s used.

            “Another thing I’ve noticed is the idea that if you write OO code, the code writes itself, and no more need for documentation, flow charts, system design, architecture maps, and the likes. Again, trying to be lazy, and not do the hard work, in order to pretend that OO code is the savior of all.”

            I don’t mean this to be insulting but that is just nonsense. If someone approaches a project and thinks the above because they code in OOPs they shouldn’t be allowed to use a calculator let alone work on any development project. And again, that is about practices not patterns.

            “I’ve kept abstraction away from that code from the beginning, and I’m thankful for it.”

            If it works for you and the type of projects you are working on great. The idea that you have to only code in OOPs or procedural is silly. You do what makes sense for the project and the people working on it. Context matters.

            “Have you ever worked on a Zend project? Have you had to go back to it years later only to lose yourself in the nested hierarchy of classes? I have. Countless times.”

            Zend is a mess with a steep learning curve. (Even Zend admits that) That has nothing to do with the value of OOPs patterns and more about a messy and poor (IMHO) framework.

            My overall point here is that you aren’t actually addressing OOPs development but practices surrounding a perception or misconception of OOPs development. (or just bad practices in general) If you are going to take the time to say something sucks, take the time to understand it first. You may grow to like it, you may not. You may see value in it, you may not. But, it certainly wouldn’t be a waste of time.

          • toach

            Also, if you are interested in exploring a GOOD php framework try codeigniter http://www.codeigniter.com/

            It is well documented, has a large community and the description on their website is right on:
            “CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.”

          • George

            You are absolutely right! I think I’ve been associating bad coding practices with OOP because I’ve seen so much of the two lately. I have seen bad practices where the previous developer tried to build everything with objects in PHP, and it just didn’t make sense.

            I will update this page as a “Why overuse of OOP sucks” instead. Coding should be smarter, not harder. I suppose that if either procedural or OOP developers write their code in a way that it makes sense, we wouldn’t have this discussion.

            Thanks for bringing some sense into my overly OOPd brain. No sarcasm intended, BTW.

            PS. I just read your latest comment. Yes, I’ve used CI on my latest two projects, and it doesn’t hurt as much anymore. 😉 I don’t like offloading the routing to PHP though. Apache is much faster to do that with its Rewrite Module. I also like it because I can be free to use procedural “helper” functions if I need, along with Modules (objects) for the data.

    • Ray

      MVC sucks and has absolutely no place in web applications…period. It’s an extremely outdated and obsolete design model.

  • toach

    I think it might be helpful to take a step back and consider the when and the why of OOP. First of all, in the beginning of your post you mention you are using Zend. Now I can’t stand Zend but even if I could I wouldn’t use it for a simple dynamic site. There is no point to it. Also, conflating zend with OOP at that level will give you a warped sense of both. Zend is OOP but OOP is not zend.

    I have noticed in your portfolio you have worked with WordPress. This may be a much better place to start in understanding the value of OOP in PHP. If you have done any custom posts types or anything with custom metadata then you would have run across this: $query = new WP_Query($args);
    With complex metadata and custom post types querying the DB can be a huge pain. Knowing that the folks at wordpress built their cms with extensibility in mind allowing developers to query data with relative ease.
    And speaking of queries, if you have worked on plugins with data outside the WP schema you will have run into the $wpdb object. Another nice feature is being able to extend classes like the WP_list_table for display of plugin data.

    I’m just scratching the surface but things may click easier if you explore OOPs PHP in a context that you are familiar with and that makes sense.

    Cheers.

  • Levente Nagy

    I dont see anything on this blog, that this sucks, this is wrong, this is band, did i say that sucks?

    You should really wake up, and get a life.

  • Andrew Schools

    I have read a lot of the comments that are in support of OOP so I will try and not regurgitate some of the other great comments here.

    One thing I like about objects is that every object is a type. I like types because you can control the structure of your data and where that data can be used. One of the things I hate most about PHP and other dynamic languages is how easy it is to create an array that hold a bunch of different types of data. These arrays are then passed around and used by many different functions. To me this is very unintuitive because within each function there is usually a loop that enumerates through the array and is riddled with checks. For example, in PHP you may see something like if (isset($myarr[‘name’]) === true) { doSomething(); }. I don’t like this because you need to place it within a loop so this check occurs during each iteration. Instead, if you created a type that implements the Iterator interface you can create a type that can be enumerated. So for example, a UserArray is an object that holds an array of User objects. The UserArray implements the Iterator interface so that it can be enumerated by PHP looping constructs. Then within your function or method signature you can force that parameter to be of that type. From there, there is no need to perform your own type checking as it is done by PHP. This really helps build a well structured application that to me is self explanatory. If I pass a UserArray type to a method or function, I know what I am getting and what I can do with it.

  • David Yue

    FINALLY ! YOU ROCK BRO !
    Procedural Style ALL THE WAY !!!! I simply do not get what this means
    $sql -> mysqli_query();
    This makes more sense: mysqli_query($sql);
    Object Oriented PHP is bound to be more and more confusing. I’m use to seeing parameters in brackets of the function and not somewhere 10 lines above it. OOPer’s complain that Procedural Style creates “spaghetti code” and is hard to read. However they fail to realize if they followed each line they would eventually understand. MOREOVER, WE NEVER TEACH OOP TO BEGINNERS ! FIND ME AN EXAMPLE IF YOU THINK NOT !!! SO WHY SHOULD WE DO IT!!!! OOP just makes things confusing and “crap like”, the code loses its logic …..

  • jonnie

    Not sure I really agree – I have worked in IT since the days of assember and the very first apple computer.

    Really all I think your rant boils down to is the observation that in a web application it is a lot more difficult to easily share large scale data models between different web pages.

    The stuff about PHP coded websites not being applications is entirely incorrect – the sequence is decision making and user input, we have the loop and branch.

    Sure frameworks lead to bloated code when people do not understand them and use them without depth of knowledge but this is not a criticism that applies to OOP in PHP.

    The gist of your rant is correct – its not easy to work with a large scale data structure between webpages but this is as much a fault of the way that the web works not PHP, you would incurr the same overhead if you wanted to lug around the same amount of data in regular non-OOP PHP.

    I would suggest that people try coding in PHP OOP and non-OOP without frameworks to get a better view of this subject – you cannot used layered technologies and then blame one at the bottom of the pile without understanding how it is used or abused by the other layers.

    Sentiment correct but badly expressed.

    People who do not know what they are doing will always find a way to write spaggetti – they can just write it faster with some newer developments.

  • jonnie

    The argument that something that ends up producing a long line of characters is not an application is just pants – most applications end up producing a long line of characters, what do you think happens when you save an intricate model of a jet fighter produced in leading edge CAD/CAM software? It will usually be saved as binary but its the same principle – its all just numbers and letters at the end of the day. I just do not understand why in your world HTML is simple and everything else is not – this is irrelevant the final HTML is simple but so is the data file from the aforementioned CADCAM example – the point is that the algorithmic procedure that generated that “simple” HTML may be arbitrarily complex and may have arbitrarily complex data structures to suit. The complexity is in the creation of that final output data – the CADCAM files for the space shuttle are just numbers and characters!

    Have you had experience of working on real large scale software projects? To suggest that the complexity of the data and algorithm is in someway linked to the medium that delivers it is an odd way to look at things – the web will not continue to serve only “simple minded” HTML documents, people want to share 3D design data, medical imaging and all kinds of complex data through the web medium – the rant does at times sound like an appeal for the old days of hand coded HTML.

  • Whenever I see a logical rant about OOP, then there is someone who brings “separation of concerns” onto the table. It is pretty classical thing in the OOP world that they just throw at “separation of concerns” and some other jargon that they even do not grasp at all.

    I do agree with George in terms of the nature of the HTTP and that is the thing that makes whole paradigm different than the classical applications.

    It is the reason many programmers do not “get” web development due to its request-response nature. They just look for something stateful in the memory out there. But, there is not. Even with caching, there is not.

    In the end, it is sending strings forth and back according to a protocol, HTTP.

    OOP is not intuitive.

    Also, another classical attitude in OOP world and OOP fanboys is they just claim that “you don’t know this XYZ thing or even you know, you don’t get this XYZ thing”.

    My answer to that fanboys, if you do not get it, it is not simple. And if it is not simple, I don’t use it.

    You know very well what I mean with “simple”. There are tons of algorithms that there are complex, but all of them for something real.

    I don’t need any smart thing to just reading from the database and responding an HTTP request. I have got everything with PHP. Read the request, find the resource it targets, prepare it and send it in the response. That is it.

    Separation of concerns, inversion of control, delegation, messaging, “methods” etc.etc. are your classical tools to answer this sort of logical rants. You don’t have any logic base that you can explain why you need them.

  • George

    I actually made a non OOP “framework” if you want to call it that. It goes back to the basics. It’s called SPAF for Single Page Application (non)Framework. http://spaf.io/ if you care to see it. No OOP, and it goes back to the basics of PHP and how it handles HTTP requests.

  • WithheldName

    The author is essentially right. A little object-oriented programming in web development goes a LONG way. You can achieve 90% of the benefits of OOP simply by using lots of functions instead. It’s when you wind up with too many functions (as in dozens or hundreds of them) that things would be conceptually simpler if you grouped some of them into classes.

    And bundling data and functions together can quickly become a mess to follow. That’s why functional programming continues to make inroads on object-oriented programming.

    And in a database application, 95% of the data is in the relational database tables! How much data do you really want or need in class objects? Creating a class object for every database table is an incredible amount of bloat for very little gain.

    OOP has become a runaway religion. Every PHP engineer these days is expected to be “solid” in OOP. But as the author points out, too much OOP quickly turns PHP into a bloated, hard-to-follow mess…with no benefits. OOP should be used carefully and sparingly in web applications.