PHP
  Home arrow PHP arrow Page 3 - Developing a Discussion Forum in PHP with Recursion
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Forums Sitemap 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Developing a Discussion Forum in PHP with Recursion
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2006-05-15


    Table of Contents:
  • Developing a Discussion Forum in PHP with Recursion
  • Getting started with the forum: defining the structure of the MySQL database table
  • Processing forums threads: defining the "ThreadProcessor" class
  • Displaying the forum: looking at the "fetchTitles()," fetchMessages()" and "createThreadForm()" methods
  • The discussion forum in action: putting the "ThreadProcessor" class to work

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Developing a Discussion Forum in PHP with Recursion - Processing forums threads: defining the "ThreadProcessor" class
    (Page 3 of 5 )

    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.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Implementing the Iterator SPL Interface
    - Building a Data Access Layer for the Data Ma...
    - Building a Singleton Database with Restricti...
    - Working with Reflected Properties with the R...
    - The Iterator, Countable and ArrayAccess SPL ...
    - Implementing the Data Mapper Design Pattern ...
    - Defining an Abstract Class with Restrictive ...
    - The Reflection API: Working with Reflected M...
    - Using Restrictive Constructors in PHP 5
    - Getting Information on a Reflected Class wit...
    - Introducing the Reflection API in PHP 5
    - Swift Mailer's Batchsend Method and Other Fe...
    - Embedding Attachments into Email Messages wi...
    - Dynamically Attaching Files with Swift Mailer
    - Using Different Paths for Attachments with S...


    Code Analysis Tools
    Enterprise code analysis tools that deliver quality and reliable code

     



    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek