How To OOP-ify

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
blacksnday
Forum Contributor
Posts: 252
Joined: Sat Jul 30, 2005 6:11 am
Location: bfe Ohio :(

How To OOP-ify

Post by blacksnday »

I am struggling to figure out how to convert my current code
(mainly functions) into an OOP approach.

The problem(and frustration) comes from the fact
that I got like 10 functions that almost all do the same thing
minus different ways of doing it.

One function displays a random news article
Another displays last 10 news article
Another display only one based on what was selected.

All three show common data:
Number of comments
Comment link
Make Comment Link
Tell Friend Link
News Article Link

Then they show different data based on which one is showing:
One random Article:
Next random Link

Only one article based on what was selected displays:
Prev/Next Links
article title/author in browser title bar

and etc.....

Now it is starting to get difficult having to seperatly code each function by
duplicating most code and having different code for each based on what it does.

I need an example of how to redo this based on OOP if
anyone is kind enough to show me?

The three functions listed above are as follows:

Code: Select all

//This is not a function but is used in the random function to 
//return the Title/Author to the Browser Title Bar

$getTitle = mysql_query("SELECT * FROM table ORDER BY RAND() LIMIT 1"); 
  while($displayTitle = mysql_fetch_array($getTitle))
   { $sitename = $displayTitle['title']; }

Code: Select all

//Shows One Random News Entry
function one_random_news_entry($sitename) { 
  $result = mysql_query("SELECT * FROM table ORDER BY RAND() LIMIT 1"); 
$title_extra = ''; 
  while ($row = mysql_fetch_assoc($result)) 
  { 
echo"
<a href='./random.php'>Keep The Bashes Coming!</a> | <a href='./submitbash.php'> Post Your Own Bash!</a> |<br />
";
	   $title_extra .= $row['row'] .'&nbsp;|&nbsp;Author:&nbsp;'. $row['name'] .' ';
	  	    $bash = $row['id']; 
	    /* get number of comments */
	    $comment_query = "SELECT count(*) FROM comments WHERE newsid='$bash'";
        $comment_result = mysql_query ($comment_query);
        $comment_row = mysql_fetch_row($comment_result);
echo "<br /><a href=\"$bash\">$comment_row[0] Comments</a>&nbsp;&nbsp;<a href=/submitcomment.php?bash=$bash>Make A Comment</a>&nbsp;&nbsp;<a href=\"/tell/bash/$bash\">Tell-A-Friend</a><br />";
    $newposts = array ( "Bash Title" => $row['title'], "Name" => $row['name'], "Bash" => $row['bash'] ); 
    foreach ( $newposts as $postfield => $postinput ) 
    { 
      $postinput = submitTags($postinput, 1, 1); 
      echo "<b>{$postfield}:</b>  {$postinput}<br />"; 
    } 
   echo "</div></div></div>";
  } 
  echo"<title>$sitename | $title_extra</title>";
}

Code: Select all

//Shows Last 10 Entries
function show_last_five_entries($url) { 
$bash = 1;
$max_results = 10; 
$from = (($bash * $max_results) - $max_results); 
$sql = mysql_query("SELECT * FROM table WHERE published = '1' ORDER BY date DESC LIMIT $from, $max_results"); 
$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM table"),0); 
$total_bashs = ceil($total_results / $max_results); 
while ($row = mysql_fetch_assoc($sql)) 
  { 
	    $bash = $row['id']; 

	    /* get number of comments */
	    $comment_query = "SELECT count(*) FROM table WHERE newsid='$bash'";
        $comment_result = mysql_query ($comment_query);
        $comment_row = mysql_fetch_row($comment_result); 
    $newposts = array ( "<a href=$url/display/bash/$bash>" => $row['bash'], "</a>\n</div>\n<b>Submitted by</b>" => $row['name'], "\n<br />\n<a href=$url/comment/bash/$bash>$comment_row[0] Comments</a>&nbsp;&nbsp;\n<a href=http://bashmyex.com/submitcomment.php?bash=$bash>Make A Comment</a>&nbsp;&nbsp;\n<a href=$url/tell/bash/$bash>Tell-A-Friend</a>\n<br /><br />" => $row['news'] ); 
    foreach ( $newposts as $postfield => $postinput ) 
    { 
      $postinput = submitTags($postinput, 1, 1); 
      echo "{$postfield} {$postinput}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; 
    } 
   } 
}

Code: Select all

// Returns News Page Links
function NewsPage($sitename) {
$bash = $row['id']; 
$bash = $_GET['bash']; 
$max_results = 1; 

if(!isset($_GET['bash'])){ 
$bash = 1;
} else { 
$bash = $_GET['bash']; 
}

$from = (($bash * $max_results) - $max_results); 
$sql = mysql_query("SELECT * FROM table LIMIT $from, $max_results"); 
$total_results = mysql_result(mysql_query("SELECT COUNT(*) as Num FROM table"),0); 
$total_bashs = ceil($total_results / $max_results); 
        /* get number of comments */
        $comment_query = "SELECT count(*) FROM table WHERE newsid='$bash'";
        $comment_result = mysql_query ($comment_query);
        $comment_row = mysql_fetch_row($comment_result);
        
if($bash > 1){ 
$prev = ($bash - 1); 
echo "<center><a href=\"/display/bash/$prev\"><<-Previous</a>     "; 
}

if($bash < $total_bashs){ 
$next = ($bash + 1); 
echo "     <a href=\"/display/bash/$next\">Next->></a><br />"; 
}

if($bash > 1){ 
$send = ($bash - 0); 
$com = ($bash - 0); 
echo "</center><br /><br />"; 
}
$title_extra = ''; 
  while ($row = mysql_fetch_assoc($sql)) 
  { 
	  $title_extra .= $row['title'] .'&nbsp;|&nbsp;Bashed by:&nbsp;'. $row['name'] .' '; 
    $newposts = array ( "<a href=$url/comment/bash/$bash>" => $row['title'], "</a>Submitted By" => $row['name'], "<a href=$url/comment/bash/$bash>$comment_row[0] Comments</a>&nbsp;&nbsp;<a href=http://bashmyex.com/submitcomment.php?bash=$bash>Make A Comment</a>&nbsp;&nbsp;<a href=$url/tell/bash/$bash>Tell-A-Friend</a><br /><br />" => $row['news'] );  
    foreach ( $newposts as $postfield => $postinput ) 
    { 
      $postinput = submitTags($postinput, 1, 1); 
      echo "<b>{$postfield}</b>  {$postinput}<br />"; 
    } 
  }
  echo"<title>$sitename | $title_extra</title>";
}

As you can see... this badly needs converted to OOP
p.s.
I know the arrays are horrible... another thing I am slowly trying to correct
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

No pun intended... But this should be posted on a PHP WTF site ;)

//Shows Last 10 Entries
function show_last_five_entries($url)
User avatar
blacksnday
Forum Contributor
Posts: 252
Joined: Sat Jul 30, 2005 6:11 am
Location: bfe Ohio :(

Post by blacksnday »

timvw wrote:No pun intended... But this should be posted on a PHP WTF site ;)

//Shows Last 10 Entries
function show_last_five_entries($url)
yea i know... since this code is only used by me...
and has not been cleaned for public usage... there are a few
errors such as that because I change stuff and then forget to change
other stuff to reflect it........

just trying to learn something.....
its always nice how seasoned devs make sure to point out
non-seasoned.....
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Ok, it seems you have already discovered that most parts of the code are the same.. Now it is up to you to find the parts that are different.

Once you have those, you factor them out into a method/function.

This allows you to have the following setup:

Code: Select all

class Links {
  function showNext() {
       $row = getNext($date);
       ....
       echo "......";
       ....
   }

   function getNext($date) {
        return ...
  }
}

class OtherLinks extends Links {
   function getNext($date)
   {
        return other..
    }
}
So you get the showNext() method in OtherLinks for "free" :)
User avatar
blacksnday
Forum Contributor
Posts: 252
Joined: Sat Jul 30, 2005 6:11 am
Location: bfe Ohio :(

Post by blacksnday »

Thanks for that!
That will help me figure out the groundwork to learn and
do it.

and yea.. i do realize my coding is bad right now :P
2months into it...
I will soon figure out a style thats not as
nasty as it is now lol.

Now that I got most of my main code running,
its time to learn OOP to simplify and make it purrrrttty!

Thanks again :)
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

The essential keyword for a good websearch: refactor(ing).

You will find out pretty soon that a testing framework helps you to check that everything is still working after each little change...
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Btw, inheritance (one class extends another) is in the case probably not the most flexible solution..

I believe a strategy pattern is more appropriate ;)

Code: Select all

class PageMaker {
  private $strategy;  

  public function setStrategy($strategy)
  {
      $this->strategy = $strategy;
  }

  public function showNext()
  {
      // do stuff
      ..
      // grab specific data
      $data = $strategy->getNext($data);
      // do stuff with data...
  }
}

public interface Strategy {
  public function getNext();
}

class Links implements Strategy {
  public function getNext() {
    // fetch from links table...
  }
}

public class OtherLinks implements Strategy {
  public function getNext() {
    // fetch from otherlinks..
  }
}
And it's pretty simple to generate a page ;)

Code: Select all

$pagemaker = new PageMaker();
$pagemaker->setStrategy(new Links());
$pagemaker->showNext();
Now you've moved the "different" parts of your original code out of the common code and can you dynamically choose with specific implementation to choose...
User avatar
blacksnday
Forum Contributor
Posts: 252
Joined: Sat Jul 30, 2005 6:11 am
Location: bfe Ohio :(

Post by blacksnday »

timvw wrote:Btw, inheritance (one class extends another) is in the case probably not the most flexible solution..
Thats the route I am gonna have to go.
My server 'could' be upgraded to php5+ but I have many other sites
on server that it just wouldn't work with.

On localhost I can attempt that route for future planning.
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Post by sweatje »

blacksnday wrote: My server 'could' be upgraded to php5+ but I have many other sites
on server that it just wouldn't work with.
You can implement the strategy pattern using PHP4 OOP just the same (with a few more & thrown into the mix).
Post Reply