SitePoint Sponsor

User Tag List

Page 2 of 2 FirstFirst 12
Results 26 to 32 of 32

Thread: OOP in PHP?

  1. #26
    SitePoint Wizard megamanXplosion's Avatar
    Join Date
    Jan 2004
    Location
    Kentucky, USA
    Posts
    1,099
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OOP is exactly what it's called, Object Oriented. For example, let's say that you are making a guestbook, these are the kinds of classes you would have...


    1. Database Abstraction Class. The database is the object in this case. Anything that doesn't deal with the database, doesn't belong here.

    2. Template Abstraction Class. The template is the object. Anything that doesn't deal with the template parser, doesn't belong here.

    3. Template Classes. Each template will be an object, each will have their own class.

    4. Form Parser. The parser is the object here and if something doesn't deal with parsing the form input, then it doesn't belong here.


    The syntax of it is simple as well. You could think of the syntax like the breadcrumb navigation that you see on all forum systems now-a-days. Home » Program Your Site » PHP » OOP in PHP?. Home is an object, the "program your site" category is an object, the PHP forum is an object, and this topic is an object. Make sense so far? Hope so.

    When dealing with classes, it is much the same way. For example...

    Code:
    <?php
    
    class template_parser {
    
        var $html, $output = '';
    
        function parse() {
            $this->html = 'Hey!';
            $this->output = $this->html;
            echo($this->output);
        }
    
    }
    
    $template = new template_parser;
    $template->parse();
    
    ?>
    In that example, the template-parser is an object. The parse() function is inside of that object, just like forums are inside of categories. Now, you can think of the syntax like a breadcrumb trail...

    $template->parse();

    If you're trying to access a function or variable inside of the class, from inside of the class, then "$this" is what you want to use.

    $this->parse();




    That's about as simple as it could get for a small example and explanation. OOP is much deeper than this, and I'm still learning it myself, however, just keep in mind that OOP is important for 2 reasons...

    1. Portability. There's nothing nice than being able to download a "template-parser object" and insert the PHP class in it's own file in your script then easily call it. This promotes the re-use of code. If you plan on taking PHP development seriously, then you should start making your own little library of functions to use. I have. You could think of this reasoning like you would clothes. Buy a shirt that's a little loose, that way if you want to re-use it later, you still can even if you have gained a few pounds. Portability is great hehe.

    2. Seperation of logical structures. Isn't it nausiating to browse through 20 PHP files to find a certain part of a script you want to edit? Wouldn't it be much easier if they had a "classes" folder which has a class for each object it deals with? Something wrong in the input parser? Go find the input parser class. That's another one of the great things of OOP.


    Of course, I am not anywhere close to being an OOP expert, I just speak what I know and hope that I helped



    EDIT: Fixed a couple of typos and I noticed Phil.Roberts posts here. It's weird seeing the Invision Power Services members all over the place on these forums

  2. #27
    SitePoint Zealot
    Join Date
    Jan 2004
    Location
    vta,ca,usa
    Posts
    180
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just some input on the $this keyword; think of it as the placeholder for the object name. When you create the class structure, you use $this because who knows what you're going to name a particular object down the road. So in the class definition, it might look something like this (no pun intended)
    PHP Code:
    class bike
    {
      var 
    $color;
      function 
    setColor($color) {
        
    // placeholder for your bike's object name
        
    $this->color $color;
      }
      function 
    returnColor() {
       
    // again, holding the place for the bike's object name
        
    return $this->color;
      }
    }

    $blue_bike = new bike();
    $blue_bike->setColor("blue");

    $red_bike = new bike();
    $red_bike->setColor("red"); 
    So in the example, you have two objects you've created, two different bikes with different colors. In the class definition, we didn't know one was going to be called $blue_bike or $green_bike or whatever, so we use $this in place of that specific object name.

    'color' is a property of the 'bike' object, so it's in effect saying $blue_bike->color = "blue"

    Personally I learned OOP structure in using Javascript objects and methods. Something about the dot notation made it simple and it stuck. You might consider looking at and experimenting with Javascript to get the idea of objects and methods prior to working with PHP OOP.

  3. #28
    SitePoint Enthusiast TMac's Avatar
    Join Date
    Dec 2002
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by coo_t2
    PHP Code:
     
     <?php
     
     
    class Player {
         
         function 
    Player($id$team$name)
         {   
    $this->id $id;
             
    $this->team $team;
             
    $this->name $name;
         }
     
         function 
    getId()
         {   return 
    $this->id;
         }
     
         function 
    getTeam()
         {   return 
    $this->team;
         }   
     
         function 
    getName()
         {   return 
    $this->name;
         }
     
     }
     
     
     class 
    NBAPlayer extends Player {
         
    // DOes nothing more than what "Player" does.
         // BUt you can add whatever you need that is 
         // specific to player in the NBA.
         // For example maybe you want to have a 
         // getFreeThrowPercentage() method?
     
    }
     
     
     
    ?>
    Think about what a Player needs to do? And what a User needs to do?
    If you can think of what these objects need to do, I'll try to help you figure out how to create them, and use them.

    --ed
    Would that not be counterproductive if the player info can all be attained procedurely from a single simple query?

    Also would it constrain my queries to a 'one size fits all' predicament?' And if I call 2 functions on 1 page would the variables that have the same names overlap and bring confusion?
    ~TMac

  4. #29
    Non-Member coo_t2's Avatar
    Join Date
    Feb 2003
    Location
    Dog Street
    Posts
    1,819
    Mentioned
    1 Post(s)
    Tagged
    1 Thread(s)
    Quote Originally Posted by TMac
    Would that not be counterproductive if the player info can all be attained procedurely from a single simple query?
    It's usually a lot simpler and quicker to do things the procedural way.
    With the OOP approach you have to put a lot more thought into it.
    You often don't reap the benefits until your system gets bigger and more complicated.

    The benefit comes in when you start adding a lot of different kinds of players of different sports. Because even though all the different player objects may
    do about the same thing, how they accomplish what they do internally may differ greatly.
    If you use the procedural approach, you might eventually find yourself
    making a bunch of decisions in your script based on the type of player.

    Like:
    PHP Code:
    while ($row mysql_fetch_assoc($playersQueryResult) )
    {
        switch (
    $row['playerType']) {
            case 
    'hockey' :
                
    // do something;
            
    break;
            case 
    'basketball' :
            
    // do something else;
            
    break;
            case 
    'baseball'   :
            
    // do something else;
            
    break;
            
    // add more as needed
        
    }

    With the OOP approach you just do something like this:

    PHP Code:
    $playerIterator =& $playerDao->getAllPlayers();

    for ( 
    $playerIterator =& $playerDao->getAllPlayers(); 
          
    $playerIterator->isValid(); $playerIterator->next()  )
    {   
        
    $playerObj =& $playerIterator->getCurrent();
        
    $playerObj->doSomething();

    You may not see much(or any) of a benefit from the above examples.
    But as time goes on and you start writing a bunch different chunks of code to get the same thing done for different types of players, it can turn messy.
    Giving all the players one consistent interface, but different implementations can keep things from getting so messy.

    This is an example of using the three main principles in OOP; inheritence, polymorphism, and encapsulation.
    All the different types of players inherit from the Player class. All the different player types inherit what their parent can do. If you want to do something different, you change it in the child class. If you want to add something, just add it.
    Polymorphism basically means(at least in the context of a loosely typed language like PHP) that 2 or more objects share the same interface(same methods).
    Encapsulation means that you don't have to care how things are done in order to use the objects. You're basically hiding all the logic behind pretty little consistent interfaces.




    Quote Originally Posted by TMac
    Also would it constrain my queries to a 'one size fits all' predicament?' And if I call 2 functions on 1 page would the variables that have the same names overlap and bring confusion?
    Not sure what you mean here. But I've been using some objects that are
    called "data access objects". These are basically objects that do all the querying for you, and just give you the data that you request.
    The $playerDao object in the example above would be and example of a data access object. It makes a query to get all the players, regardless of type of sport,
    and returns an iterator object, which in turn returns a player object for each
    iteration. The reason to use a data access
    object is so you don't have database-type-specific code scattered all throughout your application. So if you change something about how data is stored, or retrieved, you only have to worry about making changes in one place in your code.

    Another benefit of using OOP is that it tends to reduce the probability of
    variable name clashes. Because you're creating less variables yourself. THe objects have their own variables, but they have their own little protected area for names, so you don't have to worry about a variable name inside a class clashing with one from outside.

    --ed

  5. #30
    SitePoint Enthusiast TMac's Avatar
    Join Date
    Dec 2002
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by coo_t2
    PHP Code:
       $playerIterator =& $playerDao->getAllPlayers();
       
       for ( 
    $playerIterator =& $playerDao->getAllPlayers(); 
             
    $playerIterator->isValid(); $playerIterator->next()  )
       {   
           
    $playerObj =& $playerIterator->getCurrent();
           
    $playerObj->doSomething();
       } 
    Would code like this go in the includes file (that holds the method libraries) or the body of a page? And also what is the function of the '=&' operator?

    Not sure what you mean here. But I've been using some objects that are
    called "data access objects". These are basically objects that do all the querying for you, and just give you the data that you request.
    What I mean to ask is if the queries would be located in the methods like below:

    PHP Code:
      class Player {
          function 
    getFootballPlayer()
          {
           
    query "select * from players where sport="football"";
          }
          function 
    getBaseballPlayer()
          {
           
    query "select * from players where sport="baseball"";
          }
      } 
    ~TMac

  6. #31
    SitePoint Wizard Chris82's Avatar
    Join Date
    Mar 2002
    Location
    Osnabrück
    Posts
    1,003
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by TMac
    Would code like this go in the includes file (that holds the method libraries) or the body of a page? And also what is the function of the '=&' operator?
    The code shown uses the class library is therefore placed in the body of a page. Usually, PHP classes are saved in their own file and then imported using require_once.

    The "=&" is the reference assignment operator. Here is an explanation of that operator: http://php.net/manual/en/language.references.php

    Quote Originally Posted by TMac
    What I mean to ask is if the queries would be located in the methods like below:

    PHP Code:
       class Player {
           function 
    getFootballPlayer()
           {
            
    query "select * from players where sport="football"";
           }
           function 
    getBaseballPlayer()
           {
            
    query "select * from players where sport="baseball"";
           }
       } 
    Based on coo_t2's example SQL statements wouldn't be in the player class. The class would just contain the methods and properties outlined in a previous post. These SQL statements instead, would be placed in a "FootballPlayerDAO" which handles retrieving players and other things.
    Based on the results from the query it creates instances of the player class.

  7. #32
    SitePoint Wizard gold trophysilver trophy
    Join Date
    Nov 2000
    Location
    Switzerland
    Posts
    2,479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just throwing another angle

    OOP makes it possible to wrap complexity in simplicity.

    Real world example: read Kev's excellent article on Advanced PHP Email. Then try to write some code which sends an HTML email with a file attachment in procedural style [spoiler - it's a nightmare to try].

    Once you've done that, head to phpMailer. Here's how to send that same email;

    PHP Code:
    require_once 'phpmailer.class.php';

    $Mail = new PHPMailer();
    $Mail->From     "me@mydomain.com";
    $Mail->To     "you@yourdomain.com";
    $Mail->Subject "The file you requested is here";
    $Mail->Body "Dear You,\nHere it is\n\nRegards,\nMe";
    $Mail->AddAttachment("./files/file.doc","Report.doc");
    $Mail->HTML TRUE;
    $Mail->send(); 
    If you ignore the strange syntax for a moment and just glance over that code - it reads like english and that's the HTML email with attachement sent. Very easy.


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
  •