Creating a Blog Application with Interpreter Classes with PHP 5

Working with interpreter classes in PHP 5 can be a useful experience for any PHP developer. Welcome to the final part of the series that began with “Building Interpreter Classes with PHP 5.” Composed of three educational tutorials, this series teaches you how to implement the interpreter pattern with PHP, by covering not only the corresponding theoretical concepts, but also showing you concrete cases where this pattern can be applied in a useful way.

Introduction

If you read the two previous articles of the series and examined the numerous code samples shown in these tutorials, it’s quite probable that building interpreter classes with PHP 5 is now a familiar process to you, which can be tackled effortlessly. Nonetheless, if this pattern doesn’t ring any bells to you, let me give you a quick introduction to how it works. In doing so, I certainly believe that you’ll be much better equipped to grasp the logic of the hands-on example that I plan to develop in this final part of the series.

In plain terms, when the interpreter pattern is implemented, on one hand there’s a class, obviously called “interpreter,” which is tasked with parsing a set of predefined commands to perform a number of specific tasks. On the other hand there’s one or more additional classes, which are responsible for sending those commands to the interpreter, in this way establishing a well-defined relationship between all these classes.

Of course, after rereading the previous definition, you might think that an interpreter class is some kind of basic parser. That’s completely correct. As you can see, the logic that drives the interpreter pattern is rather easy to understand and implement with functional PHP code. Therefore, in this final installment of the series, I’m going to demonstrate how to get the most out of this handy pattern by developing a highly expansible blogging application. The application will be able to insert, update and delete blog entries, using a simple MySQL database as backend.

Having established the topics that will be covered in the next few lines, let’s move on and learn together how to apply the interpreter pattern to build a simple blogging system. Let’s begin now!

{mospagebreak title=Working with MySQL}

Definitely, a good point to start developing the blog application that I mentioned in the introduction is with defining a pair of MySQL processing classes. These will allow interaction with the database server in a seamless way. We’re creating these classes because we want to have at our disposal a programmatic mechanism that facilitates the insertion, update and deletion of blog entries with minor hassles.

All right, now that you know why I decided to define these simple MySQL wrappers, take a look at their respective definitions. They’re as follows:

// define ‘MySQL’ class
class MySQL{
   private $conId;
   private $host;
   private $user;
   private $password;
   private $database;
   private $result;
   const OPTIONS=4;
   public function __construct($options=array()){
     if(count($options)!=self::OPTIONS){
       throw new Exception(‘Invalid number of connection
parameters’);
     }
     foreach($options as $parameter=>$value){
       if(!$value){
         throw new Exception(‘Invalid parameter ‘.$parameter);
       }
       $this->{$parameter}=$value;
     }
     $this->connectDB();
   }
   // connect to MySQL
   private function connectDB(){
     if(!$this->conId=mysql_connect($this->host,$this-
>user,$this->password)){
       throw new Exception(‘Error connecting to the server’);
     }
     if(!mysql_select_db($this->database,$this->conId)){
       throw new Exception(‘Error selecting database’);
     }
   }
   // run query
   public function query($query){
     if(!$this->result=mysql_query($query,$this->conId)){
       throw new Exception(‘Error performing query ‘.$query);
     }
     return new Result($this,$this->result);
   }
}

// define ‘Result’ class
class Result{
   private $mysql;
   private $result;
   public function __construct(&$mysql,$result){
     $this->mysql=&$mysql;
     $this->result=$result;
   }
   // fetch row
 
  public function fetchRow(){
     return mysql_fetch_assoc($this->result);
   }
   // count rows
   public function countRows(){
     if(!$rows=mysql_num_rows($this->result)){
       throw new Exception(‘Error counting rows’);
     }
     return $rows;
   }
   // count affected rows
   public function countAffectedRows(){
     if(!$rows=mysql_affected_rows($this->mysql->conId)){
       throw new Exception(‘Error counting affected rows’);
     }
     return $rows;
   }
   // get ID form last-inserted row
   public function getInsertID(){
     if(!$id=mysql_insert_id($this->mysql->conId)){
       throw new Exception(‘Error getting ID’);
     }
     return $id;
   }
   // seek row
   public function seekRow($row=0){
     if(!is_int($row)||$row<0){
       throw new Exception(‘Invalid result set offset’);
     }
     if(!mysql_data_seek($this->result,$row)){
       throw new Exception(‘Error seeking data’);
     }
   }
}

As you can see, the two MySQL processing classes listed above are indeed very easy to follow, not only because of their intrinsic definitions, but because I used them in some of my previous PHP tutorials, published here on the prestigious Developer Shed network.

The previous MySQL wrappers provide connectivity to the mentioned database server and perform some useful tasks with it, such as running queries, seeking and counting database rows, finding insertion IDs and so forth. As you’ll see shortly, this group of database-related tasks will come in handy for processing diverse blog entries in a straightforward way.

So far, so good. After building the two MySQL processing classes that you learned a few lines above, it’s time to take the next step toward the development of the blog application that I discussed in the beginning.

As you may have guessed, this step will consist of creating both a programmatic model of a typical blog entry via a simple PHP class, and building a blog interpreter which will be responsible for adding, updating and deleting these entries by implementing the homonymous pattern in conjunction with MySQL. Sounds fairly simple, right?

All these crucial topics will be covered in the following section, so keep reading to learn more about them.

{mospagebreak title=Defining a basic blog interpreter class}

In accordance with the concepts that I just deployed in the prior section, I’m going to build a simple PHP class. It will be merely a logical representation of a typical blog entry, where all its attributes, including its title, author and content will be saved as class properties.

After defining this blog class, I’m  going to create a couple of additional classes for processing the corresponding blog entries by using the interpreter pattern. But I’m getting ahead of myself, so for the moment, please examine the signature of the class below. It represents a conventional blog entry. Its definition is as follows:

// define ‘Blog’ class
class Blog{
   private $title;
   private $author;
   private $text;
   public function __construct($title,$author,$text){
     if(!$title){
       throw new Exception(‘A valid blog title must be
supplied!.’);
     }
     if(!$author){
       throw new Exception(‘A valid blog author must be
supplied!.’);
     }
     if(!$text||strlen($text)>1024){
       throw new Exception(‘A valid blog text must be
supplied!.’);
     }
     $this->title=$title;
     $this->author=$author;
     $this->text=$text;
   }
   // get blog title
   public function getTitle(){
     return $this->title;
   }
   // get blog author
   public function getAuthor(){
     return $this->author;
   }
   // get blog text
   public function getText(){
     return $this->text;
   }
}

As indicated above, the “Blog” class that I just defined is a basic representation of a simple blog entry, where all its properties can be easily retrieved via the corresponding accessing methods. As you can see, the logic implemented by this class is in fact very easy to grasp, so you shouldn’t have major problems understanding how it works.

Well, now that you have learned the definition corresponding to the previous “Blog” class, have a look at the respective signatures of the following classes, which are tasked with inserting, updating and deleting blog entries by implementing the interpreter pattern.

Having said that, these brand new classes look like this: 

// define ‘BlogHandler’ class
class BlogHandler{
   private $mysql;
   public function __construct(MySQL $mysql){
     $this->mysql=$mysql;
   }
   // add new blog
   public function insertBlog(Blog $blog){
     $title=$blog->getTitle();
     $author=$blog->getAuthor();
     $text=$blog->getText();
     $this->mysql->query("INSERT INTO blogs
(id,author,title,text) VALUES
(NULL,’$author’,'$title’,'$text’)");
   }
   // update existing blog
   public function updateBlog(Blog $blog,$id){
     $title=$blog->getTitle();
     $author=$blog->getAuthor();
     $text=$blog->getText();
     $this->mysql->query("UPDATE blogs SET
title=’$title’,author=’$author’,text=’$text’ WHERE id=’$id’");
   }
   // delete blog
   public function deleteBlog($id){
     $this->mysql->query("DELETE FROM blogs WHERE id=’$id’");
   }
}

// define ‘BlogInterpreter’ class
class BlogInterpreter{
   private $blogHandler;
   public function __construct(BlogHandler $blogHandler){
     $this->blogHandler=$blogHandler;
   }
   public function interpret($blogCommand,Blog $blog,$id=”){
     if($blogCommand!=’insert’&&$blogCommand!
=’update’&&$blogCommand!=’delete’){
       throw new Exception(‘A valid blog command must be
supplied!.’); 
     }
     // parse ‘insert’ command
     if($blogCommand==’insert’){
       $this->blogHandler->insertBlog($blog);
     }
     // parse ‘update’ command
     elseif($blogCommand==’update’){
       $this->blogHandler->updateBlog($blog,$id);
     }
     // parse ‘delete’ command
     else{
       $this->blogHandler->deleteBlog($id);
     }
   }
}

If you studied the signatures of the above two classes, then you’ll have to agree with me that they demonstrate in a friendly fashion how to build a basic blog application that uses the schema imposed by the interpreter pattern.

As you can see, the first “BlogHandler” class is responsible for interfacing directly with MySQL to perform the insertion, update and deletion of blog entries respectively, while the second class, called “BlogInterpreter,” is tasked with parsing a set of predefined commands for performing all the aforementioned blog-related operations.

Now do you see how the interpreter pattern is used in this case to build this simple blog application? I’m sure you do!

All right, at this point you hopefully understand how all the previous classes do their business, therefore I think it’s time to show how they can be used all together in one practical example. This will demonstrate the functionality of the interpreter pattern.

Want to see how this concrete example will be developed? Go ahead and read the following section. I’ll be there, waiting for you.

{mospagebreak title=The interpreter pattern in action}

As I stated in the section that you just went through, below I included an illustrative example of how to use the interpreter class to add some blog entries to a sample “blogs” database, update one of them, and finally delete another entry.

Of course, all of these MySQL-related operations are performed according to the commands accepted by the interpreter. This clearly demonstrates the functionality provided by this pattern.

That being said, here is how the example in question looks:

try{
   // connect to MySQL
   $db=new MySQL(array(‘host’=>’host’,'user’=>’user’,'password’=>’password’,
‘database’=>’database’));
   // create ‘BlogHandler’ object
   $blogHandler=new BlogHandler($db);
   // create ‘BlogInterpreter’ object
   $blogInt=new BlogInterpreter($blogHandler);
   // create some sample blog entries
   $blog1=new Blog(‘Blog 1′,’Alejandro Gervasio’,'This is the
content of blog 1′);
   $blog2=new Blog(‘Blog 2′,’John Doe’,'This is the content of
blog 2′);
   $blog3=new Blog(‘Blog 3′,’Susan Smith’,'This is the content of
blog 3′);
   // insert sample blogs into database
   /*
   $blogInt->interpret(‘insert’,$blog1);
   $blogInt->interpret(‘insert’,$blog2);
   $blogInt->interpret(‘insert’,$blog3);
   */
   // update existing blog
   /*
   $blog2=new Blog(‘Updated Blog 2′,’John Doe’,'This is the
updated content of blog 2′);
   $blogInt->interpret(‘update’,$blog2,2);
   */
   // delete existing blog
   //$blogInt->interpret(‘delete’,$blog3,3);
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As shown in the above example, implementing a basic blog application using the schema dictated by the interpreter pattern is actually a straightforward process, which can be achieved with minor efforts. In this case, the previous example first creates three different blog objects, which are inserted into the corresponding database table via the interpreter.

Next, this time following a similar approach, the second blog entry is updated, and finally another row is deleted from the pertinent database table. Of course, as you see, all of these operations are performed by using the interface provided by the interpreter object. Quite simple to achieve, right?

Finally, I’d like to point out one last thing before I finish this tutorial: feel free to modify the source code of all the classes shown here, so you can eventually have a more solid background on how the interpreter pattern works.

Final thoughts

Sadly, we’ve come to the end of this series. I hope that all the code samples included here will be useful enough to expand your existing knowledge of pattern-based programming with PHP.

See you in the next PHP tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan