SitePoint Sponsor

User Tag List

Results 1 to 17 of 17
  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2001
    Location
    Wolverhampton, UK
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    why use classes???

    now, if i can be given an answer to why they are useful i'll start usin' them

    give me some examples of uses of classes and say y they are useful please

    just curious,
    beachball

  2. #2
    SitePoint Wizard TWTCommish's Avatar
    Join Date
    Aug 1999
    Location
    Pittsburgh, PA, USA
    Posts
    3,910
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Freddy will surely come in with his guestbook example of OOP (which is quite useful, by the way). The short of it is (to me, at least) a useful tool when dealing with large, complex applications. It's handy for abstraction: for modular code.

    Sick of all the slogans and buzzwords? Me too. Let me give you an example...

    Note: I rarely use OOP and my code may not work...but hopefully it will give you an idea of how this stuff works

    First, let's create a simple class, called "person":

    PHP Code:
    <?php
      
    class person {
        var 
    name;
        var 
    age;
        var 
    gender;

          function 
    print_details() {
            print 
    $this->name   "<br>";
            print 
    $this->age    " years old<br>";
            print 
    $this->gender "<br>";
          }
      }
    Now, here it is in action (assuming the code above is inside the same script, or included from another script):

    PHP Code:
    $myperson = new person();
    $myperson->name "Bob";
    $myperson->age 30;
    $myperson->gender "Male";
    $myperson->print_details(); 
    Now, unless I messed up (I'll bet I did miss something somewhere), that should print out this:

    Code:
    Bob
    30 years old
    Male
    Not only that, but I believe you can, if you want to save some space, setup your class to accept some parameters right away...so that when you create a new instance of that object, you can fill in it's "details" in one line, like this:

    PHP Code:
    $myperson = new person("Bob"30"Male");
    $myperson->print_details(); 
    Not gonna get into that just yet...hopefully this will give you an idea of how it works, and, perhaps, how it can be useful.
    Last edited by TWTCommish; Jul 22, 2001 at 16:37.

  3. #3
    Node mutilating coot timnz's Avatar
    Join Date
    Feb 2001
    Location
    New Zealand
    Posts
    516
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Also, if you have a function in your class, with the same name as the class, it will get run when you first initiate the class, so it is useful for setting up variables etc for later use in the class. Waiting for the guestbook OOP example freddy.

    I don't use them much, probably due to the nature of my scripts, and their uses etc, but I have used one or two lately, when they have been appropriate (ie, I felt like using them).

  4. #4
    SitePoint Enthusiast
    Join Date
    Jul 2001
    Location
    Wolverhampton, UK
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thx every1

    where is the guestbook example

    i keep seein' on me travels peeps talkin' about using classes for definin' a seesion not sure why this is useful or what is achieved by it, but it seems like a reasonably common use...

    well to me neway

    beachball

  5. #5
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Okay I will show you the guestbook example, however, I am slowly leaning towards a more embedded approach as it seems the class approach parses slower than the traditional PHP mixed with HTML example.

    Okay I couldn't find the guestbook example, I'll post it later tonight. Here is a calendar example. I am no expert in OOP so please be gentle if you happen to know more than I about OOP. I am sure there are several things I could have done to make it a bit better, but I think you can get the idea from this. Basically the main benefit I find is the modular type code where you can plug it in and modify to fit your sire with little effort.

    (Source Code)
    http://www.irq11.com/~louie/calendar/calendar.phps



    You'll see the benefit when it comes time to use this on a site. You can simply use the following code.

    (Working Example)
    http://www.irq11.com/~louie/calendar/caltest.php

    (Source Code for example)
    http://www.irq11.com/~louie/calendar/caltest.phps





    Enjoy and please make any recommendations on how I might improve on the OOP part of it.
    Last edited by freddydoesphp; Jul 23, 2001 at 12:45.
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  6. #6
    SitePoint Evangelist jkh1978's Avatar
    Join Date
    May 2001
    Location
    Northern Virginia
    Posts
    445
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    guest book

    Does sitepoint have a directory of php code like the calendar and message board?

  7. #7
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The message board is vbulletin. The calendar is just a script I wrote a while back and feel free to use it for your needs.
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  8. #8
    Grumpy Mole Man Skunk's Avatar
    Join Date
    Jan 2001
    Location
    Lawrence, Kansas
    Posts
    2,066
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow freddy - that's a really nice Calendar

    Since you asked for suggestions though - I'd dump those global variables (eeugh) and send the month and year variables in the constructor instead (defaulting them to nothing):

    function calender($month = '', $year = '')

    That way you can still do $calendar = new calender; to create a calendar for today, or do $calender = new calender($month, $year) for a certain year.

    One thing that could be good is if the class was designed so that it had one method which deals with generating the text in the "day" boxes. That way it would be ridiculously easy to create a new class that extends your calendar and over-ride that one method with a method that pulls information out of a database or something, making it easy to use your calendar as something that shows information abnout dates.

  9. #9
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Skunk, actually I have another version tucked away that ties in with phplib to add database connectivity and dynamic event generation on the calendar. Here is the code.

    Test script and source code
    http://www.irq11.com/~louie/calendar/caltest_db.php
    http://www.irq11.com/~louie/calendar/caltest_db.phps

    Calendar Class w/db support source code
    http://www.irq11.com/~louie/calendar/calendar_db.phps


    The variable that is in the link from the calendar is named hotday and I will leave it up to you guys to display the evenst from that day after the day has been clicked.
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  10. #10
    Node mutilating coot timnz's Avatar
    Join Date
    Feb 2001
    Location
    New Zealand
    Posts
    516
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cool, thanks freddy!
    Oh no! the coots are eating my nodes!

  11. #11
    ********* Callithumpian silver trophy freakysid's Avatar
    Join Date
    Jun 2000
    Location
    Sydney, Australia
    Posts
    3,798
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Asking what are the advantages of using classes, is a little like asking a nudist what is the advantage of not wearing clothes - in that nudism is an aproach to life or a philosophy. In the same way, Object Oriented software development is a whole way of developing software that is not just about classes. The object oriented approach starts at the user requirements analysis phase and extends through design, coding and testing, and lives on through maintenance and refactoring.

    So what has all that got to do with whipping up a web page? Exactly! IMHO, the bigger and more complex the system, the more advantageous the object-oreinted approach is. Freddydoesphp's code does however, highlight one of the main advantages to using classes for web scripting - reusability. If you were chatting to freddy about setting up a calender he could tell you - "I've written a Calender class you can use". Brilliant, all you have to do is include the file that contains the code for the class, instantiate an object from it and start using the class methods to get it to do what you want to do. Thus it is a very clean way to reuse code because the required data members (variables) and functions are all packaged up neatly inside the class. In this way a class provides a user with an "interface". All you need to know is what the class is called and what its methods (functions) are and what their signatures are and you can use an object of that class in your code without needing to worry about "how it works" on the inside.

    To take it further. Lets say that freddy's class doesn't quite do everything you want. You can use class inheritence to inherit freddy's class into a new class and then simply add a function to the new class or rewrite the implimentation of another function, without having to rewrite all the code and reinvent the wheel.

    In my mind, the biggest advantage of classes is polymorphism. In a very simplistic way, you could say that the PEAR::DB class provides polymorphism. What this means is that the same class and interface can be used within your scripts to access one of many differnt types of database. Right now, the way I write my scripts is that I use the mysql_xxx() functions which have been written as PHP wrappers to the MySQL C API. If I want to change my database to PostgreSQL, I would have to rewrite every single call to a mysql_xxx() functions. If I wanted to write all my code to be able to handle different databases, I could use the PEAR::DB class. I just create a DB object at the begining of my script and pass the information about which physical db I am using in the constructor along with all the server, uid, pword details. Every time I want to execute a SQL query, I call the appropriate function of class DB in my code. Thus if I do want to change the actual db I am using, I only need to modify the call to the class constructor and don't have to wade through my code and change every mysql_xxx() function call. Here is an article about PEAR::DB that will expand and explain this example more http://www.onlamp.com/pub/a/php/2001/05/24/pear.html

    So what the PEAR::DB class does is provide a layer of abstraction between the actual DB being used and your program. It provides a standard interface that you can use to access a DB in all your code, hiding the implimentation details from the programmer. I'm sure you will see that there are advantages and disadvantages to this and that there are reasons for and against using something like the PEAR::DB class to interface with a DB.

    That is a very crude example of polymorphism, because polymorphism is much more than what I describe about. However it is also a very religious topic and there are those that would even argue that Java lacks "true" polymorphism.

    Returning to my earlier remarks about the usefullness of classes in web scripting, I believe it does come down to the complexity of the system you are creating, the degree to which you want to be able to reuse code in a modular manner, and the degree to which you want to spend time up-front designing classes over just scripting away stream-of-consciousness style in a very RAD manner.

    There are several articles about programming classes in PHP around the web such as at www.phpbuilder.com . However, returning to my remarks about nudism, there is a degree to which you have to grok the object-oriented "way-of-life" to make them useful in your design.
    Last edited by freakysid; Jul 24, 2001 at 07:14.

  12. #12
    SitePoint Enthusiast
    Join Date
    Jul 2001
    Location
    Wolverhampton, UK
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks 4 that freakysid...

    that has helped a lot

    i would like to make my code more modular so that as i create new stuff -i were gonna try a calendar soon newys and classes seem very useful because i will be able to use a similar sort of thing on all my pages with only having to change the presentation aspect which will take about 2 seconds

    beachball

  13. #13
    PHP warrior dkode's Avatar
    Join Date
    Sep 2001
    Location
    Planet Namek
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nice class freddy,

    You mentioned that the OOP aaproach is slower then wrapping it all into the php?

    One suggestion for your class is this:

    In the parts where you are outputting HTML, I would suggest that you attach a style sheet to your main *.php files and in turn you could pass the style names into your class. Therefore If someone wanted to add extra parameters into the style tags we would just have to change the style sheet. It looks like you made a style sheet already in there from the looks of the %s parts of the <span style> tags. This would work, my method is just a suggestion. I always try to make the styles as scalable as possible because my clients always seem to change their mind on me... "Ohh can i have the link in hot pink?!"


    Ya know, that kinda stuff.
    "Mankind cannot define memory, yet it defines mankind"
    -- Project 2501, Ghost in the Shell

    Smarty | PEAR | PHP Manual | MySQL Manual

  14. #14
    Dumb PHP codin' cat
    Join Date
    Aug 2000
    Location
    San Diego, CA
    Posts
    5,460
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually since you mention it, my class is pretty weak to be bluntly honest and to the point. It was my first real attempt and something remotely resembling OOP. I plan on rewriting most if it, to break it apart a little more and allow for more user customization. I also want to separate out the html layout from the logic. I just need a spare few days to dedicate to it. I also opted out of using a style sheet and instead inline styles for a reaon, and one that I cannot think of right now. I did do it for a reason, it might not have been a good reaon, but there was a method to the madness. Thanks for the input.
    Please don't PM me with questions.
    Use the forums, that is what they are here for.

  15. #15
    Digital Warrior Renegade's Avatar
    Join Date
    Nov 2000
    Location
    Portland, OR
    Posts
    480
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Question.

    Freakysid,(or anyone) What is the difference between creating a class for database stuff, versus just creating some standard database funtions using non-OOP?

    For instance, how about just

    db_connect();
    db_query();
    db_insert();
    db_update();
    db_disconnect();

    ...functions instead?

    When it comes time to port your code to another database, you need only change the functions, and not the calls.

    Does OOP/polymorphism provide any benefit over doing it this way?
    Last edited by Renegade; Oct 3, 2001 at 12:09.
    --There's my 1.5 cents, now where is my change!?!?

  16. #16
    SitePoint Wizard TWTCommish's Avatar
    Join Date
    Aug 1999
    Location
    Pittsburgh, PA, USA
    Posts
    3,910
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I think OOP's value lies in that of larger, more complex applications...because you're right: functions work quite well when it comes to databases. I use functions in my scripts to connect to the DB...if I do switch to classes, it will only be to try to become more comfortable with objects.

  17. #17
    Don't eat yellow snow spaceman's Avatar
    Join Date
    Mar 2001
    Location
    Melbourne, Australia
    Posts
    1,039
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Originally posted by Renegade
    Question.

    Freakysid,(or anyone) What is the difference between creating a class for database stuff, versus just creating some standard database funtions using non-OOP?

    For instance, how about just

    db_connect();
    db_query();
    db_insert();
    db_update();
    db_disconnect();

    ...functions instead?

    When it comes time to port your code to another database, you need only change the functions, and not the calls.

    Does OOP/polymorphism provide any benefit over doing it this way?
    Hi Renegade - I just found this old (but still valid, I think) article on DevShed that might answer your question:

    http://www.devshed.com/Server_Side/PHP/Class/

    I only found this article because I'm also trying to make the big decision myself about whether or not to go forward with the use of classes.

    The key phrase in the artile that *I think* answers your question is "This is going to be a problem as soon as you have a page that needs two concurrently active queries, because these queries would fight for the global variables".

    But correct me if I'm wrong.
    Web Design Perth Melbourne .:. Itomic Business Website Solutions
    Drupal Experts .:. Drupalise


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
  •