SitePoint Sponsor

User Tag List

Page 1 of 3 123 LastLast
Results 1 to 25 of 52
  1. #1
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    OOP vs Old School PHP

    Hi everyone, I am a traditional php coder that is trying to make the decision to switch to Object Oriented PHP. I have read some articles, watched some videos, and I am still not convinced it is worth switching to.

    From what I gather the pro- oop folk seem to say that with oop you can:
    1. Create reusable blocks of code
    2. Have cleaner code
    3. Be Easier to update
    4. Be Easier for multiple programmers to work on
    5. Be better for complex projects
    6. Make the jump to other languages easier


    But from my perspective using good old functions accomplishes all these things listed as well, and not one article or video i have found actually goes into any depth or real comparison as to why or how the oop way is actually better, they just say that it is.

    I would love some real examples and comparisons between oop and old school functions. Or should i just stick with old school functions?

    I am sure this topic has been brought up many times before, but what i want to see is real side by side comparisons to why one way is better than the other. From my perspective it seems like oop is more verbose than the way i do things now.

    thanks for any input.

  2. #2
    SitePoint Addict
    Join Date
    May 2008
    Location
    Missouri, USA
    Posts
    273
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not an expert programmer but I made the switch to object oriented php about 9 months ago. I went back to look at a project I finished a year ago and was surprised by how messy it looked. In my opinion, OO code just looks cleaner and is much easier to follow.
    Another big one that you also mentioned is re usability. I've not been working in OO long but i've already created some components which i've been able to reuse with very little effort.
    Follow Me On Twitter: BryceRay

  3. #3
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,810
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    OOP is an entirely different way of looking at programming compared to structured programming. Making the shift from one style to the other is much harder than learning a few dozen new languages in a style you already know.

    Yes structured programming does provide the various features to an extend but it is only scalable to a point and once you start talking tens of millions or trillions of lines of code then structured programming just isn't going to provide those options to the required level.

    It is mainly a matter of scale and if you only have a few thousand lines of code you are not going to get a huge benefit out of using OOP unless you make use of someone else's objects as the building blocks with which your program is constructed (and you are probably already doing that even if you don't know OOP).

    ere are some benefits (off the top of my head) that OOP has over structured programming.

    1. Grouping of related functions because they are all part of one object rather than just separate functions.
    2. A heirarchical approach to programming where bigger objects are constructed from smaller objects rahter than a spagetti tangle of function calls.
    3. A greater ability to reuse existing code because the code is grouped into a smaller number of objects that contain all the related functionality rather than being scattered across dozens or hundreds of different functions where you can't tell which functions are dependent on what other functions.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  4. #4
    SitePoint Addict Mastodont's Avatar
    Join Date
    Mar 2007
    Location
    Czech Republic
    Posts
    375
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by jsbarra View Post
    real side by side comparisons to why one way is better than the other
    Inheritance is great improvement if you know how to use it. Basic (abstract) class defines common properties and methods, higher (derived) classes contain only differences. In procedural code you'll end with a bunch of deep nested IFs or switches.

    E.g. basic class Product with properties Name, UnitPrice, Manufacturer etc. ... and derived Car with added Speed, EngineType etc.

    felgall:
    1. Grouping of related functions because they are all part of one object rather than just separate functions.
    I would prefer to extend this - Grouping of related functions with shared variables (properties) ... e.g. database class DBStructure with methods IsStringField, IsDateField, IsFieldInTable etc. and shared array (class member) with table schema. Simple grouping is rather worthless.

  5. #5
    SitePoint Guru bronze trophy TomB's Avatar
    Join Date
    Oct 2005
    Location
    Milton Keynes, UK
    Posts
    989
    Mentioned
    9 Post(s)
    Tagged
    2 Thread(s)
    The biggest single difference between OOP and Procedural code is that data and behavior are combined in an object.

    In procedural code, your data is not linked to the behaviour.


    Lets take a simple example. Imagine a forum system where different user levels see different things.

    Procedural code:
    PHP Code:
    <?php
    //assume $user is an array such as array('id' => 1, 'name' => 'Tom', ...); and is used throughout the page as the currently logged in user


    $result mysqli_query('SELECT userId, title, message FROM messages WHERE topicId = ' mysqli_real_escape_string($_GET['topicid']));
    while (
    $row mysqli_fetch_array($result)) {
        if (
    $user['type'] == 'admin' || $user['id'] == $row['userId']) {
            
    //show edit button
        
    }
        
    //show rest of topic
    }
     
    ?>
    Looks sound? Perhaps, but it's likely the if statement is repeated in multiple places. What if we add a new user type, such as moderator who also needs to see that edit button? Now every occurance needs to be changed.

    Can we fix that?

    PHP Code:
    <?php
    //assume $user is an array such as array('id' => 1, 'name' => 'Tom', ...); and is used throughout the page as the currently logged in user

    $result mysqli_query('SELECT userId, title, message FROM messages WHERE topicId = ' mysqli_real_escape_string($_GET['topicid']));

    function 
    canEdit($user$message) {
        return (
    $user['type'] == 'admin' || $user['id'] == $message['userId']);
    }

    while (
    $row mysqli_fetch_array($result)) {
        if  (
    canEdit($user$row)) {
            
    //show edit button
        
    }
        
    //show rest of topic
    }
    ?>
    We've separated the logic. Makes sense, and this is actually a step towards what OO tries to ahieve.


    Now, what if there are complete different coniditions for each user type, e.g. for normal users, they can edit the post within 15 mins:

    PHP Code:
    <?php 
    function canEdit($user$row) {
        if (
    $user['type'] == 'admin') {
            return 
    true;
        }
        else if (
    $user['type'] == 'moderator') {
            
    $result mysqli_query('SELECT count(*) as count FROM moderator_permissions ... ');
            
    $row mysqli_fetch_array($result);
            return 
    $row['count'] > 0;
        }
        else {
            return (
    $user['id'] == $message['userId']);
        }    
    }
    ?>
    This is starting to get messy, what happens when there are 10 different user types? Maybe for some boards I don't want to allow users to edit their posts.

    This function has the potential to get very long with a lot of potentially nested if statements.


    We can remove that whole if block using OOP.

    PHP Code:
    <?php 
    class User {
        public 
    $id$name$email//...

        
    public function canEdit($message) {
            return 
    $this->id == $message->userId;
            
    //really would be $this->id == $message->user->id but we'll keep it simple to be in line with the previous examples 
        
    }
    }

    class 
    Admin extends User {
        public function 
    canEdit($message) {
            return 
    true;
        }
    }

    class 
    Moderator extends User {
        public function 
    hasPermission($board) {
            
    //...Reusable and *not* tied to the single canEdit function
        
    }
        
        public function 
    canEdit($message) {
            return 
    $this->hasPermission($message->board);
        }
    }

    ?>
    And now the page itself looks something like:

    PHP Code:
    <?php 
    //some logic to use the result of the user query to decide what user type to create. Would use a factory pattern, which is far beyond the scope of this example
    while ($message mysqli_fetch_object($result'message')) {
        if  (
    $user->canEdit($message)) {
            
    //show edit button
        
    }
        
    //show rest of topic
    }
    ?>
    Which is now far more scalable and reusable. By storing the behaviour with the data, we've avoided the need for if statements in the canEdit function. This makes the whole system far more flexible. This type of object substitution is known as 'polymorphism' and is probably the most powerful tool in OOP.

  6. #6
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    67
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi 4 a newbie to php would it be in my best interest to learn OOP or Procedural code?

  7. #7
    Non-Member
    Join Date
    Jul 2009
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    For me OOP is the way i think and it helps me a lot to develop the code. OOP is considered slower than Procedural code.

    The good thing about OOP is that you can reuse the code with minimal modifications. Also imagine if you have a 20000 lines project and using no objects... It is very difficult to maintain it (atleast for me). Also objects allow many programmers to work simultaneously by coding different parts of the projects.

    PHP is not the best example of OO language and it does not support all the Object features that other languages do (example C#).

    To make the long story short, i would suggest you to use the style that you feel more comfortable. You can try objects. you might love them.

  8. #8
    Non-Member
    Join Date
    Jul 2009
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by W3bnewbie View Post
    Hi 4 a newbie to php would it be in my best interest to learn OOP or Procedural code?
    if you have experience on OOP you can start using objects. If not it's easier to start writing procedural code.

  9. #9
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    67
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks & I've no experience in oop or procedural code. but will like to learn oop as I'll learn other languages easy this from what I take..... & any good place to learn oop? concepts besides google.....
    thanks again

  10. #10
    PHP Guru lampcms.com's Avatar
    Join Date
    Jan 2009
    Posts
    921
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OOP is something that is more of a concept than a php-related thing. It will take extra time to learn, so if you are a total newbi to php, then you would have to learn the php and also the OOP, and then some php-specific OOP things.

    Javascript OOP is completely different from any other OOP.

    But it's all worth it to learn OOP and only use OOP in php.

  11. #11
    Grumpy Minimalist
    Join Date
    Jul 2006
    Location
    Ontario, Canada
    Posts
    424
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is my favorite example for the benefits of OOP, albeit somewhat outdated after 7 years: What's so good about OOP?

  12. #12
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    75
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have heard people say that OOP is particularly useful for shared projects.

    That said, it isn't necessary sometimes.

    HTML, CSS, XML, and SQL are not object-oriented. You can use OO code to generate them, but to me that seems like trying to kill an ant with a gun.

  13. #13
    SitePoint Guru glenngould's Avatar
    Join Date
    Nov 2005
    Posts
    661
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Paul Graham thinks a little bit different about OOP: Why Arc Isn't Especially Object-Oriented

    Quote Originally Posted by Paul Graham
    ...I personally have never needed object-oriented abstractions....
    Tweep List adds an avatar menu to Twitter (open source)
    Word Stats shows your most used words on Twitter

  14. #14
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for all the responses, especially for tomb for the real examples. that has helped more than anything. From Tomb's example, i do like getting rid of those if statements. But I still am not sold. The way I structure my PHP is through use of functions that i call from an include file, that from my perspective, are clean, easy to update, and in some cases less code than the oop way. Am I crazy for thinking that? Will my current methods be consider bad practice?

  15. #15
    SitePoint Enthusiast nrg_alpha's Avatar
    Join Date
    Dec 2008
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you really want to get on the ball with programming, I definitely think learning OOP is a must imo. OOP contains significant benefits that procedural code doesn't.

    When dealing with classes (properly structured classes), you get plenty of benefits including inheritance, composition/aggregation, deligation, encapsulation and abstraction. (you'll learn about these concepts as you learn OOP - hopefully - so don't let those terms gloss your eyes over like a deer in the headlights). Well designed classes translates into robust, reusable, decoupled functionality that is open to change through extensibility without fear of 'breaking' your system (really, REALLY important!).

    I think you really have to start learning it to begin to truly appreciate the advantages it offers. Admittedly, it's not a small, light subject to learn. Getting your head around concrete and abstract classes, interfaces and whatnot isn't so bad (at least, not im my opinion). The trickier part is learning design patterns, which are a set of systems built to solve specific problems in time tested tried-and-true forumlas. But one must learn to crawl before learning to do backflips. One step at a time

    Sure, procedural programming is easier and as such, seems better.. but once you start learning OOP, you'll start to really see the benefits emerge.

    The only warning is that saying (when holding a hammer, everything looks like a nail). OOP isn't designed for everything under the sun. Procedural coding has its place and purpose, as does OOP. Knowing when to make use of OOP is important as well.

    Finally, learning OOP is a benefit with regards to learning other languages, like say, Java, C# and C++, as these are OOP-based languages!

  16. #16
    SitePoint Member mi6crazyheart's Avatar
    Join Date
    Aug 2009
    Location
    INDIA
    Posts
    2
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think as long as you've not the clear experience about both the approach of programming you really can't able to understand how & in which sense the both approach is different from each other. So, I'll suggest..... straight just jump over to OOP's technique & build u'r stuff rather thinking & confusing a lot. After that you'll automatically get the whole idea why & how OOP's is much more better than earlier(functional) approach of programing.

  17. #17
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You definitely don't need to use oop to write good code. You can write good php code without a lick of oop.

    But, IMO, learning oop will change the way you program for the better, even if you don't actually end up writing a lot of oop code afterwards. It gives you a different perspective. Personally, It didn't really click for me trying to learn it with php. So I got a java book that really beat the core concepts into my brain. It made a huge difference, and I don't regret the time investment.

  18. #18
    SitePoint Addict
    Join Date
    Feb 2005
    Location
    Maine
    Posts
    244
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by crmalibu View Post
    You definitely don't need to use oop to write good code. You can write good php code without a lick of oop.

    But, IMO, learning oop will change the way you program for the better, even if you don't actually end up writing a lot of oop code afterwards. It gives you a different perspective. Personally, It didn't really click for me trying to learn it with php. So I got a java book that really beat the core concepts into my brain. It made a huge difference, and I don't regret the time investment.
    I agree with this. PHP was the first language I learned, and it was self taught. I liked doing things procedurally, but I would occasionally make a poorly designed class. I didn't really understand OOP, and I was always against taking programming classes. But then I took a CompSci course with a great teacher at my school and learned Java, where object oriented design is a requirement. When I started coding some PHP again, OOP seemed like common sense.


  19. #19
    SitePoint Guru
    Join Date
    Jun 2006
    Posts
    638
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    jsbarra: I used to code the way you do, and my sites were done in half the time it usually took other people to do them. (That's because they were all organized correctly and so on.)

    BUT, that way of codding have 2 problems, and those are apparent only after you did / maintained a few sites (lets say 100+sites):

    Problem 1:
    - You find a "bug" in your code, and you know that this code has been used in 50 sites.

    "Old School PHP" solution:
    -- Go to the site where you found the bug, and do a fix, creating a patch (to be merged in all other sites).
    -- Go in each site, see if that site is using your "buggy" code, and add the patch. if your lucky, you don't get many conflicts...
    --- Then go in and test each site, 1 by 1 to make sure that change did not break anything. You do this by testing from the client side, and by looking at all the code.

    "OOP" solution:
    -- Go to the site where you found the bug, and do a fix, creating a patch (to be merged in all other sites), and the tests sets to go with your change.
    -- Since your site is OOP (good OOP), your change will affect 1 class only.
    -- Go in each site, see if that site is using your "buggy" code, and add the patch.
    NOTE: since your code is good OOP, you will never have conflicts here, since all 100 sites have the exact same class.
    -- Then, you go through each site, and run your automated tests. Those tests will test your entire site, letting you know if everything is wrong or if it's all good. Since each site has it's own tests, you can even make a small script to run them all.
    This is where you save time, instead of YOU having to check everything to make sure it's done right, you get a script to do it, making you lose 15 minutes, and lets say 1h of CPU time, vs a few days of your time (witch, since your only human, is more prone to errors).


    Problem 2:
    - You did some of these sites 2-3 years ago, and are not 100% sure what the hell were you thinking when you wrote that code, BUT you know you have to add this 1 small little feature. (or your adding functionality to someone else's code)

    "Old School PHP" solution:
    - Go around the old code, try to figure out what is used where, and make sure that your change will not break anything. Since this is old code, you have to REALLY pay attention to what your doing, since we all know that adding a -1 in a unisigned field will end up with a 42,234,123 value that you will waste a night to figure out where it came from.

    "OOP" solution:
    - Go around the code, find out what class is involved in your change, do the change, do the new tests for the new change, run the automated test case. if all good, test a bit in your browser, else, the tests sets will let you know what you broke. (and you don't have to waste all night looking for what's wrong / hopping nothing went wrong)


    OOP will also save you time since, if done right (and that does not mean to only apply the concept to your PHP code/classes, but also you your includes/html/css), all your functionality is in one place, (Ex: only 1 place to load a Profile from the DB), making it easier to find bugs/fix/modify that 1 place, instead of having to go around fixing 15 places for 1 change.

    In short, OOP will not save you time if your codding 1-2 small sites for yourself, or if your doing freelancing, making small sites for clients that will never get back to you. But it will save you time if your the one that will have to maintain the actual sites you produce, and if yoru making allot of them / bigger ones.

    Hope that helps.

    ps:
    - your first few OOP projects will be WAY worst than what you currently have ("Old School PHP" style). But once you make a few, you will realize the benefits and will never be able to go back to your old ways (it will just feel stupid when you code the old way).

  20. #20
    PHP/Rails Developer Czaries's Avatar
    Join Date
    May 2004
    Location
    Central USA
    Posts
    806
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Vali View Post
    "OOP" solution:
    - Go around the code, find out what class is involved in your change, do the change, do the new tests for the new change, run the automated test case. if all good, test a bit in your browser, else, the tests sets will let you know what you broke. (and you don't have to waste all night looking for what's wrong / hopping nothing went wrong)
    OOP does not automatically give you unit tests, but you seem to make it sound that way. Tests are a component of TDD and Agile development practices, not OOP itself. The benefits you listed are not direct benefits of OOP.

  21. #21
    SitePoint Guru
    Join Date
    Jun 2006
    Posts
    638
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Czaries, it doesn't, but makes it WAY easier to add them.

  22. #22
    PHP/Rails Developer Czaries's Avatar
    Join Date
    May 2004
    Location
    Central USA
    Posts
    806
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Vali View Post
    Czaries, it doesn't, but makes it WAY easier to add them.
    No doubt. Just pointing out to those who are learning OOP that automated tests are not something that comes with it. The benefits you highlighted are those of TDD and Agile methodologies, so I was just making that clear.

  23. #23
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    107
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right on, thanks to everyone for their input, I think I'll take a leap of faith and start foling around with oop and see if it sticks.

  24. #24
    SitePoint Wizard frank1's Avatar
    Join Date
    Oct 2005
    Posts
    1,392
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    one truth is that, when php started it was known for its simplicity....so every body jumped in....web programming was never so easy....

    then the traditional programmer(java,perl,C) saw great fan following with php....and they decided to turn php to other programming language..(like C ,java,.NET and some others...)

    They were some how able to convince people that their way of programming(JAVA,C etc) would bring more power to PHP....the main people or most php people got convinced...and we could see whole php is changing into other language especially in the name of frameworks....

    May be the so called OOP way (which was being used in other languages like java) was able to add some power but every one forget that that so called power was gained at the cost of simplicity....

    For eg when a traditional php programmer sees jooma's code or may be symfony framework's code...she asks...is it really php? or she is not able to program straight away...

    so i fear some day,java coding and php coding will be same....(at least in structure and way)

    if some body ask me,i think php people should be first thought how to gain power retaining the simplicity...rather than opting for C,JAVA OOP style directly....

    and to be frank most of these frameworks and all are based on microsoft .net framework concept...(they are brining what is being done in .net as tools and naming it framework...for eg CRUD operations and validations..and many more...)

    so people are changing php in the name of OOP ....which may be good...but every one is forgetting about simplicity....where the real pwer of the php lie..and php is turing into other languages....

    i imagine if somebody could have brought those features(what is done in good OOP) in traditional fashion without losing simplicity,php would have been one the most powerful language for ever....

  25. #25
    SitePoint Enthusiast PHP_Adam's Avatar
    Join Date
    Jan 2009
    Location
    West Yorkshire, UK
    Posts
    92
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    frank1, is correct about OOP being an "add on" to PHP. It was not designed for simplicity.

    You can tell this by looking for tutorials or examples theirs too many about Procedural code, yet OOP their is not.
    Those tutorials that are out their are written for people who already know OOP, so its hard to get your foot in.
    I tried to change that, but failed. I still don't feel confident in my OOP PHP, but at least now understand it.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •