HomePHP Page 3 - Developing a Discussion Forum in PHP with Recursion
Processing forums threads: defining the "ThreadProcessor" class - PHP
If you’re interested in learning how to use recursion in PHP, look no further. Welcome to the third (and last) tutorial of the series “Recursion in PHP.” In three parts, this series walks through the fundamentals of recursive functions in PHP, in addition to explaining how to define and utilize recursive methods in object-based applications.
Basically, I plan to make the forum work by using a single PHP class, called "ThreadProcessor," which is responsible for displaying threads and adding new posts to the pertinent forum. As you'll see shortly, this class will aggregate an additional one, named "MySQL," handy for providing the forum with the capacity to connect to MySQL and run SQL queries.
Having explained the basic tasks that will be performed by the "ThreadProcessor" class, here is its corresponding definition. Please have a look at it:
class ThreadProcessor{ // declare data members var $db; var $threadCode; var $threadSubmitted; var $user; var $email; var $title; var $message; function ThreadProcessor(&$db){ $this->db=&$db; // instance of MySQL class $this->threadCode=!$_GET['threadcode']?'0':$_GET ['threadcode']; $this->threadSubmitted=$_POST['send']; $this->user=$_POST['user']; $this->email=$_POST['email']; $this->title=$_POST['title']; $this->message=$_POST['message']; } // display main-child threads & thread form function displayThreads(){ // add new thread to database if($this->threadSubmitted){ $this->addThread(); } ob_start(); // display threads $this->threadCode=='0'?$this->fetchTitles():$this- >fetchMessages(); // display thread form $this->createThreadForm(); $contents=ob_get_contents(); ob_end_clean(); return $contents; } // display main threads function fetchTitles(){ $result=$this->db->query("SELECT * FROM forum WHERE parent_id='$this->threadCode'"); echo '<ul>'; // loop over result set while($row=$result->fetchRow()){ echo '<li><a href="'.$_SERVER['PHP_SELF'].'? threadcode='.$row['id'].'">'.$row['title'].'</a> Posted by ('.$row['name'].') '.$row['email'].'</li>'; $this->threadCode=$row['id']; // call recursively the 'fetchTitles()' method $this->fetchTitles(); } echo '</ul>'; } // display child threads function fetchMessages(){ $result=$this->db->query("SELECT name,title,message FROM forum WHERE id='$this->threadCode'"); if($result->countRows()==0){ echo 'No messages were found!'; return; } $row=$result->fetchRow(); echo '<h2>'.$row['title'].'</h2><hr /><p>'.$row['name'].' wrote: '.$row['message'].'</p><a href="'.$_SERVER['PHP_SELF'].'? threadcode=0">Back to main threads</a>'; } // display thread form function createThreadForm(){ $this->threadCode=intval($_GET['threadcode']); echo '<form method="post" action="'.$_SERVER ['PHP_SELF'].'?threadcode='.$this->threadCode.'"><h2>Post your new message</h2>'; echo 'Name <input type="text" name="user" size="30" /><br />Email <input type="text" name="email" size="30" /><br />'; echo 'Title<input type="text" name="title" size="30" /><br />Message<br /><textarea name="message" rows="10" cols="30"></textarea><br /><input type="submit" name="send" value="Add thread" /></form>'; } // add new thread function addThread(){ $this->db->query("INSERT INTO forum (id,parent_id,name,email,title,message) VALUES (NULL,'$this- >threadCode','$this->user','$this->email','$this->title','$this- >message')"); header('location:'.$_SERVER['PHP_SELF']); } }
As shown above, the "ThreadProcessor" class exposes a few handy methods for displaying forum threads, as well as for adding new posts to the "forum" database table, something that is achieved by coding a regular online form.
As I said a few lines above, the class aggregates an instance of a "MySQL" class that comes in quite useful for connecting to MySQL and running queries against the database table. As you can see, this class is aggregated and assigned as a new property inside the respective constructor.
Now, take a look at the signature of the "displayThreads()" method:
function displayThreads(){ // add new thread to database if($this->threadSubmitted){ $this->addThread(); } ob_start(); // display threads $this->threadCode=='0'?$this->fetchTitles():$this- >fetchMessages(); // display thread form $this->createThreadForm(); $contents=ob_get_contents(); ob_end_clean(); return $contents; }
In essence, what this method does is determine the course of action to be taken, in accordance with the value of the "threadCode" property. First, it checks whether the form for adding new posts has been submitted, and according to this, calls the "addThread()" method, since a new message has been posted by a user. After checking this condition, the method displays either the corresponding thread titles or the contents of submitted messages. Finally, it shows the form for posting new messages, by calling the "createThreadForm()" method.
Before proceeding to review other methods of the "ThreadProcessor" class, let me first clarify one point: notice the entire visual output is echoed to an output buffer; the data is not displayed directly on the browser. I have a good reason for doing this: since the "fetchTitles()" method calls itself (yep, here's where recursion comes in), it generates a dynamic output for each method instance, which is easily captured by the output buffer, instead of troubling things with regular variables. Additionally, the remaining methods also use this buffer to output their contents, which are returned to calling code.
Right, now that you understand the reasons for using an output buffer, the next step consists of looking at the remaining methods of the "ThreadProcessor" class, to give you a clear idea of how they fit together. Therefore, please click on the link below and keep on reading.