SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Addict Huscy's Avatar
    Join Date
    Jul 2002
    Location
    Newcastle, UK
    Posts
    318
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help me with my first attempt at OOP (bit long)

    Hi, this is my first attempt at OOP, and is used to administrate a flat file affiliate system, at the moment it can add an affiliate, display X number of random affiliate buttons (without repeating any), and find an affiliate, and includes some very basic validation - can anyone tell me if I am making any big mistakes so far?

    PHP Code:
    class affiliate {
     
         var 
    $filename;
         var 
    $handle;
         var 
    $needle;
         var 
    $field;
         var 
    $mode;
         var 
    $id;
         
         
    // Gets handle of file, and return either the handle, or an error message if it coudn't get the handle
         
    function gethandle($filename,$mode) {
             
    $this->filename $filename;
             
    $this->mode $mode;
             
    // Store the possible modes in an array
             
    $modes[0] = "r";
             
    $modes[1] = "r+";
             
    $modes[2] = "w";
             
    $modes[3] = "w+";
             
    $modes[4] = "a";
             
    $modes[5] = "a+";
             
    $modes[6] = "x";
             
    $modes[7] = "x+";
             
    // If the mode given is valid, attempt to make handle, if not then give helpful error message
             
    if(in_array($this->mode,$modes)) {
                 
    // If the handle is valid resource, return the handle, if not show helpful error message
                 
    if($this->handle fopen($this->filename,$this->mode)) {
                     return 
    $this->handle;
                 } else {
                     
    $this->error('Could not connect to the file - '.$this->filename.' using mode '.$this->mode);
                 }
             }
             else {
                 
    $this->error('The mode '.$this->mode.' is not valid and cannot be used!');
             }        
         }
         
         
    // Function to add an affiliate to the file, with auto-incrementing ID
         
    function addaffiliate($afffile,$affname,$thumbname,$afflink,$filename) {
             
    $this->afffile $afffile;
             
    $this->affname $affname;
             
    $this->afflink $afflink;
             
    $this->thumbname $thumbname;
             
    $this->filename $filename;
             
    // Initialise $this->id to 0
             
    $this->id 0;
             
    // Use the getarray method, to get an array getid[] containing named keys
             
    $this->getid $this->getarray($this->filename);
             
    // Loop through the ID field of the getid[] array, and make the ID = the IDs already in the file if they are bigger
             
    foreach($this->getid["id"] as $value) {
                 if(
    $this->id $value) {
                     
    $this->id $value;
                 } 
             }
             
    // Add one to the $this->id variable, so that it is one greater than the biggest ID already in the file
             
    $this->id++;
             
    // If the thumbnail file is successfully copied, continue - if not give an error message
             
    if(copy($this->afffile,"images/".$this->thumbname)) {
                 
    // Make a string to write to the file, seperated by commas, and add a newline (\n) to the string to mark the end of the record
                 
    $towrite $this->affname.",".$this->thumbname.",".$this->id.",".$this->afflink.",0 \n";
                 
    // If the writing of the string was successful (using the gethandle method) then close the file, and refresh the page
                 
    if(fwrite($this->gethandle($this->filename,"a+"),$towrite)) {
                     
    // Close the file
                     
    fclose($this->handle);
                     
    // Notify user that file writing is in progress
                     
    echo("Writing to file...<br />");
                     
    // Print HTML code to refresh page
                     
    echo('<meta http-equiv="Refresh" content="3,testfiles.php?">');
                 } else {
                     
    // Tell user that the string could not be written to the file
                     
    $this->error('Could not write to file.');
                 }
             } else {
                 
    // Tell the user that the thumbnail could not be copied
                 
    $this->error('Could not copy thumbnail.');
             }
         }
         
         
    // Function to return an array with the Name, Thumbnail URL, Thumbnail ID and Hits in seperate keys
         
    function getarray($filename) {
             
    $this->filename $filename;
             
    // Make array of the contents of the filename passed into the function
             
    $file_array file($this->filename);
             
    // Loop through however many records are in the file
             
    for($i=0;$i<count($file_array);$i++) {
                 
    // Make new array by seperating string by commas, after trimming whitespace off the end
                 
    $data_array explode(',',trim($file_array[$i]));
                 
    // Assign the name key (0)
                 
    $affrow["name"][$i] = $data_array[0];
                 
    // Assign the thumbnail URL key (1)
                 
    $affrow["thumb_url"][$i] = $data_array[1];
                 
    // Assign the ID key (2)
                 
    $affrow["id"][$i] = $data_array[2];
                 
    // Assign the link key (3)
                 
    $affrow["link"][$i] = $data_array[3];
                 
    // Assign the hits key (4)
                 
    $affrow["hits"][$i] = $data_array[4];
             }
             
    // Return the array containing named keys 
             
    return $affrow;
         }
         
         function 
    checkrand($needle,$haystack) {
             
    $this->needle $needle;
             
    $this->haystack $haystack;
             if(
    in_array($this->needle,$this->haystack)) {
                 return 
    TRUE;
             } else {
                 return 
    FALSE;
             }
         }
         
         
    // Function to return either bool TRUE or FALSE depending whether the $needle is found in the $field field of the array of the file $filename
         
    function find($filename,$needle,$field) {
             
    //---------- FIELD KEY ---------//
             // 0 = Name field
             // 1 = Thumbnail URL
             // 2 = Thumbnail ID
             // 3 = Thumbnail Link
             // 4 = Hits Generated by Button
             
    $this->field $field;
             
    $this->filename $filename;
             
    $this->needle $needle;
             
    // Make array of file supplied in parameters
             
    $file_array file($this->filename);
             
    // Loop through file array, x times based on the number of records in the array
             
    for($i=0;$i<count($file_array);$i++)
             {
                 
    // Split up array into fields - Name, Thumbnail URL, Thumbnail ID and Hits generated by button
                 
    $data_array explode(',',trim($file_array[$i]));
                 
    // Loop through data array
                 
    foreach($data_array as $key=>$value)
                 {
                     
    // Show key and value, uncomment when debugging
                     // echo($needle.' - '.$value.'<br>');
                     // If the value passed is equal to the needle, AND in the correct field (as to avoid confusion between ID and Hits fields) then return
                     // TRUE, and move the array pointer to the end of the array to minimise processing time (dont compare when already found)
                     
    if($value == $this->needle && $key == $this->field) {
                         return 
    TRUE;
                         
    end;
                     }
                 }    
             } 
         }
         
         
    // Function to seed a random number
         
    function make_seed() {
             list(
    $usec$sec) = explode(' 'microtime());
             return (float) 
    $sec + ((float) $usec 100000);
         }
         
         
         function 
    getrandom($numdisplay,$filename) {
             
    $this->numdisplay $numdisplay;
             
    $this->filename $filename;
             
    $display '';
             
    $idlist $this->getarray($this->filename);
             for(
    $i=1;$i<$this->numdisplay 1;$i++) 
             {
                 if(!isset(
    $already)) {
                     
    srand($this->make_seed());
                     
    $randnum rand(1,count(file($this->filename)));
                     if(
    $this->find($this->filename,$randnum,2)) {
                         
    $already[$i] = $randnum;
                         
    $randnum--;
                         
    $display .= '<a href="'.$idlist["link"][$randnum].'"><img src="images/'.$idlist["thumb_url"][$randnum].'" /></a> ';
                     } else {
                         
    $this->error('The affiliate with ID - '.$randnum.' was not found.');
                     }        
                 } else {
                     
    srand($this->make_seed());
                     
    $randnum rand(1,count(file($this->filename)));
                     while((
    $this->checkrand($randnum,$already))) {
                         
    srand($this->make_seed());
                         
    $randnum rand(1,count(file($this->filename)));
                     }        
                     if(
    $this->find($this->filename,$randnum,2)) {
                         
    $already[$i] = $randnum;
                         
    $randnum--;
                         
    $display .= '<a href="'.$idlist["link"][$randnum].'"><img src="images/'.$idlist["thumb_url"][$randnum].'" /></a> ';
                     } else {
                         
    $this->error('The affiliate with ID - '.$randnum.' was not found.');
                     }        
                  }
             }
         return 
    $display;
         }
         
         
    // Function to check that the affiliate thumbnail is either a .gif or a .jpg
         
    function checkimage($afffile) {
             
    $this->afffile $afffile;
             
    // Size variable is an array containing information about the file submitted by the form
             
    $size getimagesize($this->afffile);
             
    // size[2] holds the file type, if it is 1 (gif) or 2 (jpg) then the function returns true, if not it returns false, and gives a helpful error message
             
    if($size[2] == || $size[2] == 2) {
                 return 
    TRUE;
             } else {
                 
    $this->error('The thumbnail must be either a .gif or a .jpg file');
                 return 
    FALSE;
             }    
         }
         
         
    // Function to display error messages
         
    function error($errormessage) {
             
    // End current code if an error is found, and display the error message
             
    die('<br />Something went wrong!<br />=>'.$errormessage.'<br />');
         }
     } 
    Thanks if anyone had the patience to read through all that, before I start, is the best method of editing & deleting things in a file to make an array of the file, edit/delete there, and then erase and re-write the file? or is there a direct (no arrays) method?

  2. #2
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I do not care to mix presentation (HTML) with business logic (and persistent storage), but to each their own.

    IMO, you should avoid the $array[0] type construct.

    PHP Code:
             // Store the possible modes in an array
            
    $modes[0] = "r";
            
    $modes[1] = "r+";
            
    $modes[2] = "w";
            
    $modes[3] = "w+";
            
    $modes[4] = "a";
            
    $modes[5] = "a+";
            
    $modes[6] = "x";
            
    $modes[7] = "x+";
            
    // If the mode given is valid, attempt to make handle, if not then give helpful error message
            
    if(in_array($this->mode,$modes)) { 
    could be rewritten easily as:
    PHP Code:
    // If the mode given is valid, attempt to make handle, if not then give helpful error message
            
    if(in_array($this->mode,array('r','r+','w','w+','a','a+','x','x+'))) { 
    This could also be done with a regular expression, i.e.
    PHP Code:
    //not tested
    if (preg_match('/^[rwax][+]?$/'$this->mode)) { 
    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.

  3. #3
    SitePoint Addict mr tinkles's Avatar
    Join Date
    Jan 2003
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    your 1st attempt????

    how long working on 1st attempt?

    how long until 2nd attempt?

    my bad. if you want to learn OOP, or anything...

    start simple.

    is used to administrate a flat file affiliate system
    do you want:

    flat object?
    file object?
    affiliate object?
    system object?

    I'd just like to know...

  4. #4
    SitePoint Addict Huscy's Avatar
    Join Date
    Jul 2002
    Location
    Newcastle, UK
    Posts
    318
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks sweatje, i'll do that

    mr itinkles - why do you sound so surprised? I cant really work on something unless it has a purpose - this is for a project whiich must be in by february, so i decided to try oop

    Im not sure what you mean - could you explain the difenences between these types of objects (or point me somewhere where I can learn?)

    Thanks

  5. #5
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    My thoughts are first you should design and write one or more classes specific to the file system yes ?

    Then this way you have that said class(es) available to your affiliate(s) on this occasion, and for future projects you will have; Most certainly you'll find the seperation of those class(es) will be helpful to you.

    You might also like to look at Iterators, ie. Look at Harry's website; www.phppatterns.com for more yes ?

    In fact, have a look anyway, since Harry also did an intro to OOP using PHP Damn good site btw, enjoy.

  6. #6
    SitePoint Addict mr tinkles's Avatar
    Join Date
    Jan 2003
    Posts
    262
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Im not sure what you mean - could you explain the difenences between these types of objects (or point me somewhere where I can learn?)
    I'm not sure where this is going, but...

    I know good OO, and then I don't.

    are you making any big mistakes? I don't know, you have the knowledge of what's happening, so ask yourself? what makes you feel you are making big mistakes?

    OO, is like everything. if know how to use, simple and effective, else bungling like mess.

    If you want to learn OO, let's continue.


    I'll try to explain the differences:

    flat object?
    I have no clue, other than using non-relational data in text files, or something else.

    file object?
    Obviously a file of some type. The file exists in whatever form it is, object or not. How you handle fiile, will be the "object". If you want to create file object class, should react same as file as it exists.

    affiliate object?
    Sound like you need to have relationship between 'affiliate' objects? As in, customer to vendor? or vendor to client? or customer to customer? affiliate hard to pin down, exactly.

    system object?

    what system? may be object like already?

    mt


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
  •