Defining the Core Structure of a PHP Blogger

In the first part of this three-part series, we’ll examine the basic outlines of creating a blog application with PHP 5. If you’re currently working with PHP 4, this program can be adapted to that version of the language.


A downloadable zip file is available for this article.

Introduction

Anyone who has been using PHP for a while knows that building fairly simple database-driven web applications is indeed a straightforward process that can be accomplished with minor headaches. Whether you’ve been developing the core engine of a small website, or creating a decent search system that uses a database backend for indexing relevant content, the truth is that PHP makes it really easy to create these kinds of applications.

True to form, building web-based systems that implement some type of interaction with a RDBMS, particularly with one as popular as MySQL, is an experience that you’ve probably tackled a dozen times, or even more if you’re a seasoned PHP developer with many hours of sleepless hard work on your shoulders.

Among the plethora of database-driven applications that you can create with PHP without having to scratch your head until you lose your hair is one that has become very popular over the last two years. I’m speaking specifically of bloggers, which allow anyone to insert easily editable content onto a website by using only a graphical front end. Of course, when I use the term "editable," I mean that all the blog entries can be updated and even deleted without having to know a pinch of web programming.

Since this powerful approach, which is also used heavily with content management systems, can be implemented in PHP with minor hassles, I’ve prepared for you a three-part series that will teach you in a friendly manner how to create an extensible blog mechanism.

Naturally, the blogger that I’ll build over the course of these articles will be provided with the capacity for performing the most common tasks associated with this kind of application, like inserting, updating and deleting blog entries, in addition to including some extra features that you’ll discover in turn in the different tutorials.

Assuming that building a blogger with PHP is really an interesting topic for you, let’s learn together how this useful application can be developed in a few easy steps. Let’s get going!

{mospagebreak title=Defining the blogger’s core structure}

Naturally, a good place to start building the blogger system with PHP 5 consists of defining its basic structure so it will be easier for you to understand how each module of the application fits together with each other module.

This being said, the blogger in question will be created by using only one PHP class. It will be responsible for performing the insertion, update and deletion of blog entries respectively, in conjunction with displaying the entire list of blogs and the corresponding online forms, handy for posting and updating a particular entry.

Considering all the prerequisites that I established before, here is the initial definition for the new "BlogProcessor" class. Take a look at its signature, please:

// define ‘BlogProcessor’ class
class BlogProcessor{
            private $mysql;
            private $blogData;
            public function __construct(MySQL $mysql){
                        $this->mysql=$mysql;
                        $this->blogData=$_POST;
            }
            // display blog system
            public function displayBlogger(){
                        // edit blog
                        if($this->blogData['editblog']){
                                   // code for displaying edit page goes here                     

                        }
                        else{
                                   // insert new blog
                                   if($this->blogData['insertblog']){
                                               $this->insertBlog();
                                   }
                                   // update blog
                                   elseif($this->blogData['updateblog']){
                                               $this->updateBlog();
                                   }
                                   // delete blog
                                   elseif($this->blogData['deleteblog']){
                                               $this->deleteBlog();       
                                   }
                        }
                        // code for displaying main page goes here
            }  
}

As illustrated above, the skeleton of the new "BlogProcessor" class is very simple to grasp (at least for now). Basically, I split up the structure of the class into two main methods. The first one is obviously the constructor that performs a few useful initialization tasks, while the second one, called "displayBlogger()," is tasked with inserting, updating and deleting blog entries, as well as displaying the corresponding forms for handling blog-related data.

However, for the moment you should ignore all the processes concerning the display of blog entries, and focus your attention on the signature of the methods listed above. As you can see, the constructor accepts an object of type "MySQL" as its unique input parameter, which comes in useful for database connectivity inside the blog processor class, running queries and processing MySQL result sets.

Don’t worry for the moment about this MySQL class, because at the end of the series you’ll be provided with all the classes required to get the blogger working. However, at least for now, you’ll have to settle for with studying the methods declared before.

Returning to the definition of the "displayBlogger()" method that belongs to the blog processor class, you’ll realize that it contains three additional private methods. These are called "insertBlog()", "updateBlog()" and "deleteBlog()" respectively, and they perform well-differentiated tasks, like inserting new entries, and updating/deleting existing ones. So far, nothing unexpected, right?

In addition, you’ll notice the use of the "$this->blogData" property as a flag for executing the different operations associated with distinct entries. In this case, I decided to use the superglobal $_POST array to do this, but this condition can be easily modified and utilize instead some variables passed in via the GET method.

All right, I believe that all the explanations that I offered before would be rather incomplete if I don’t show you a few screen shots that illustrate the look and feel that I plan to give to the blog system. Therefore, here are the corresponding images:

As you can see, the three pictures included above demonstrate in a clear fashion the different screens that will be presented to the user to perform the insertion of entries, as well as the update and deletion of them. In addition, I showed you the panel that displays the complete list of blogs, which means that at this point, you should have an accurate idea of how the blogger system will look at first glance.

Well, having defined the general structure of the corresponding "BlogProcessor" class, it’s time to move on and start coding each one of the private methods that were declared previously to perform the insertion, update and deletion of blog entries. Sounds interesting, doesn’t it?

To learn how these important methods will be defined, keep reading.

{mospagebreak title=Defining the insertBlog() method}

Before I proceed to define the signature of the method responsible for adding new entries to the blog application, let me first explain briefly how I’m going to create the corresponding database schema with MySQL. In simple terms, I’m going to use only one table, called "blogs" (yep, my own creativity sometimes blows me away), which will contain the following fields: "ID," "title," "author," "content" and finally a column named "date."

As you’ll imagine, each one of the referenced fields will house the ID of a particular blog entry, its title and date, the name of the author who posted it and lastly the content in question. Definitely, after having at hand the description of all the corresponding fields that comprise the "blogs" database table, creating its structure is reduced to something as simple as this:

CREATE TABLE blogs (
            id INTERGER(4) UNSIGNED AUTO_INCREMENT, PRIMARY KEY,
            author VARCHAR(45) NOT NULL,
            title VARCHAR(45) NOT NULL,
            content LONGTEXT NOT NULL,
            date TIMESTAMP
)

All right, now that you know how the previously-defined "blogs" database table has been properly defined, have a look at the following method that belongs to the "BlogProcessor" class. It is called "insertBlog()" and is tasked with adding new entries to the referenced table:

// insert new blog
private function insertBlog(){
$title=$this->blogData['title'];
            $author=$this->blogData['author'];
            $content=$this->blogData['content'];
            $this->mysql->query("INSERT INTO blogs (id,author,title,content,date)
VALUES (NULL,’$author’,'$title’,'$content’,TIMESTAMP(10))");
            header(‘Location:’.$_SERVER['PHP_SELF']);                            
}

As you’ll certainly agree, the above method is quite straightforward. It merely inserts a new blog entry into the respective "blogs" database table, and uses the values entered on the corresponding web form to perform the insertion process. Finally, the method finishes its execution by redirecting the user to the same web document where all the blogs will eventually be displayed. Simple and efficient, right?

At this stage, and assuming that the method you saw before isn’t difficult to understand, let’s move forward and see together how to define another method included with the "BlogProcessor" class, which will be useful for updating a particular blog entry.

As usual, to see how this will be done, please click on the link below and keep reading.

{mospagebreak title=Defining the updateBlog() method}

As I said in the previous section, the next step involved in creating the blog application relies on defining yet another handy method, aimed at updating an existing entry in the corresponding database table. This brand new method not surprisingly has been called "updateBlog()," and its definition is as follows:

// update blog
private function updateBlog(){
            $id=$this->blogData['id'];
            $title=$this->blogData['title'];
            $author=$this->blogData['author'];
            $content=$this->blogData['content'];
            $this->mysql->query("UPDATE blogs SET
title=’$title’,author=’$author’,content=’$content’,date=TIMESTAMP(10) WHERE
id=’$id’");
            header(‘Location:’.$_SERVER['PHP_SELF']);
}

As shown above, the signature for the "updateBlog()" method looks nearly identical to the previous "insertBlog()" method. In this case, the only difference rests on the type of database operation that it performs, since it updates an existing blog entry instead of adding a new one.

After a particular blog has been updated, the method reloads the main page where the complete set of blogs is conveniently displayed. Quite possibly, if you used to work on a frequent basis with DML operations, you’ll find the prior method pretty simple to understand. What do you think?

Well, at this point I provided you with a fairly decent explanation of how the previous "insertBlog()" and "updateBlog()" methods do their business. Therefore, it’s time to examine the last method that I plan to include in the "BlogProcessor" class; in this case, I’m talking about the one called "deleteBlog()" and obviously it is responsible for removing a specified entry from the "blogs" database table.

Curious about how this new method will be coded? Go ahead and read the following section.

{mospagebreak title=Defining the deleteBlog() method}

As you may guess, removing existing blog entries from the respective "blogs" database table is only a matter of running a DELETE command, wrapped up in a new class method. For this specific case, I decided to name this method "deleteBlog()" and its definition is listed below. Have a look at it:

// delete blog
private function deleteBlog(){
            $id=$this->blogData['id'];
            $title=$this->blogData['title'];
            $author=$this->blogData['author'];
            $content=$this->blogData['content'];
            $this->mysql->query("DELETE FROM blogs WHERE id=’$id’");
            header(‘Location:’.$_SERVER['PHP_SELF']);
}

As you can see, the above "deleteBlog()" method first removes a specified entry from the corresponding "blogs" database table, and then reloads the main web page, in this way updating the display of all pertinent blogs. As I explained in a previous section, you shouldn’t be concerned yet with how the "BlogProcessor" class will display the different user panels that I showed you a few lines before, since this topic will be covered over the course of the next article.

At this stage, I have provided you with a concise explanation of how the blog processor class adds a new entry to the respective database table, in addition to showing the signature of the methods tasked with updating and deleting exiting blogs.

Thus, this is a good time to list the new definition of the "BlogProcessor" class, after including the mentioned methods. Here is how this class now looks:

// define ‘BlogProcessor’ class
class BlogProcessor{
            private $mysql;
            private $blogData;
            public function __construct(MySQL $mysql){
                        $this->mysql=$mysql;
                        $this->blogData=$_POST;
            }
            // display blog system
            public function displayBlogger(){
                        // edit blog
                        if($this->blogData['editblog']){
                                   // code for displaying edit page goes here
                        }
                        else{
                                   // insert new blog
                                   if($this->blogData['insertblog']){
                                               $this->insertBlog();
                                   }
                                   // update blog
                                   elseif($this->blogData['updateblog']){
                                               $this->updateBlog();
                                   }
                                   // delete blog
                                   elseif($this->blogData['deleteblog']){
                                               $this->deleteBlog();       
                                   }
                        }
                        // code for displaying main page goes here
            }
            // insert new blog
private function insertBlog(){ 
                        $title=$this->blogData['title']; 
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("INSERT INTO blogs
(id,author,title,content,date) VALUES (NULL,’$author’,'$title’,'$content’,TIMESTAMP
(10))");
                        header(‘Location:’.$_SERVER['PHP_SELF']);                            

}
            // update blog 
            private function updateBlog(){ 
                        $id=$this->blogData['id'];
                        $title=$this->blogData['title'];
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("UPDATE blogs SET
title=’$title’,author=’$author’,content=’$content’,date=TIMESTAMP(10) WHERE
id=’$id’");
                        header(‘Location:’.$_SERVER['PHP_SELF']);


            // delete blog 
            private function deleteBlog(){ 
                        $id=$this->blogData['id'];
                        $title=$this->blogData['title'];
                        $author=$this->blogData['author'];
                        $content=$this->blogData['content'];
                        $this->mysql->query("DELETE FROM blogs WHERE id=’$id’");
                        header(‘Location:’.$_SERVER['PHP_SELF']);

}
}

Okay, above you have the completely updated version of the "BlogProcessor" class. As I mentioned previously, there are still numerous methods that need to be defined, but this will be performed in the following article of the series. In the meantime, study the source code of all the methods shown here and feel free to introduce your own improvements, or if you want to skip over these steps, download this zip file containing the core files of the application (the same link is included at the beginning of this article).

Wrapping up

In this first part of the series, I’ve drawn some basic outlines for how to create a blog application with PHP 5. Due to its versatility, the program can be easily adapted to work with PHP 4, in case you’re currently working with that version of the language.

However, there are many interesting topics to cover yet. Over the next article, I’ll define all the remaining methods required by the "BlogProcessor" class to display the complete list of blogs, as well as for rendering the corresponding web forms for inserting and updating database entries. See you there! 

Google+ Comments

Google+ Comments