Creating a Blog Application with Interpreter Classes with PHP 5 - The interpreter pattern in action (
Page 4 of 4 )
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!