Manipulating String Literals with Interpreter Classes in PHP 5

Among the huge variety of design patterns that can be easily implemented in PHP 5, the interpreter is one that might be particularly interesting to you. It allows you to build effortlessly the so-called parser layers. Welcome to the second installment of the series that began with “Building Interpreter Classes with PHP 5.” Made up of three parts, this series introduces the core concepts on this useful pattern, and also complements its theory with numerous educational hands-on examples.


Stepping back for a moment to the preceding article of the series, I’m pretty sure that all the concepts deployed in that tutorial concerning the concrete implementation of the interpreter pattern in PHP 5 will be familiar to you now. However, if that’s not the case, let me remind you quickly how this pattern works, so you can grasp more easily all the code samples that I plan to include in this article.

In plain terms, where this pattern is applied, there’s a class, usually called “interpreter,” which is responsible for parsing a predefined set of commands. These commands are sent out by one or more additional classes. As you can see, this definition is easy to understand because it is similar to the concept of parsers.

However, building interpreter classes is by far a much simpler process than developing full-featured parsers. I hope to demonstrate this by showing you some didactical code samples, where this pattern will be mostly used as a simple yet efficient parsing layer.

Bearing in mind that in the first article of the series I illustrated how to use an interpreter class to handle a group of fictional users, in this tutorial I’m going to go teach you how to utilize this pattern for manipulating a set of string processing classes.

By the end of this tutorial, you should be equipped with a solid background in how the interpreter pattern works. This may be very useful to you, particularly if you’re taking your first steps into pattern-based programming with PHP 5.

Now, having outlined the topics that will be covered in the next few lines, it’s time to move on and continue learning more on how to build interpreter classes. Let’s get started now!

{mospagebreak title=Handling literals}

In accordance with the concepts expressed in the introduction, I’m going to demonstrate how to implement the interpreter pattern by developing a simple mechanism which will come in handy for processing basic string literals.

Essentially, I’m going to define a class which will perform a few useful tasks. These tasks will include loading and saving an inputted string to a specified text file, as well as calculating the length of the string in question. As you can see, all these tasks sound fairly easy to execute, meaning that the structure of this string processing class is very simple.

And speaking of that, here is the definition for this class, so take a look at its source code:

// define ‘StringSaver’ class
class StringSaver{
   private $dataFile;
   private $data;
   public function __construct($data=’This is the default
       throw new Exception(‘Input data must not be an empty
       throw new Exception(‘Invalid destination file!’);
   // load string from destination file
   public function loadString(){
       throw new Exception(‘Error reading string from destination
     return $this->data;
   // save string to destination file
   public function saveString(){
       throw new Exception(‘Error opening destination file!’);
       throw new Exception(‘Error writing string to destination
   // determine length of string
   public function getStringLength(){
       throw new Exception(‘Error determining length of data
     return $length;

Not surprisingly, the signature that corresponds to the previous “StringSaver” class is really easy to grasp. As I said before, the tasks performed by this class are limited to loading and saving a given string to a target text file, along with returning the length of that string to calling code.

However, at this point there’s not a single clue about how to include an interpreter class that can work in conjunction with the string processor that you learned a few lines above. In the next section, I’m going to define the basic structure of an interpreter class, in this way implementing the programmatic model dictated by the homonymous pattern.

Having said that, and assuming that you’re interested in learning how this interpreter class will be built, I suggest you click on the link that appears below and read the following section.

{mospagebreak title=Defining a string interpreter class}

As I expressed in the section that you just read, the only piece required to complete the schema imposed by the interpreter pattern is an interpreter class. This class should be capable of parsing a bunch of predefined commands to process a given data string in some useful way.

Below I listed the definition of a brand new interpreter class. As I explained previously, it will be capable of parsing a number of specific string commands.

Please examine the signature of this string interpreter class, which looks like this:

// define ‘StringInterpreter’ class
class StringInterpreter{
   private $stringSaver;
   public function __construct(StringSaver $stringSaver){
   // parse string commands
   public function interpret($command){
       throw new Exception(‘A valid user command must be supplied
to parse data string!’);
     // parse ‘lowercase’ command
       return strtolower($this->stringSaver->loadString
     // parse ‘uppercase’ command
       return strtoupper($this->stringSaver->loadString());
     // parse ‘reverse’ command
       return strrev($this->stringSaver->loadString());
     // parse ‘length’ command
       return strlen($this->stringSaver->loadString());

As you can see, the logic implemented by the prior “StringInterpreter” class is fairly easy to follow. Similar to the interpreter that I created in the preceding article of the series, this class also presents a method, called “interpret(),” which not surprisingly is tasked with parsing a predefined number of string commands.

In this case, the class in question has been provided with the ability to execute four different instructions, named “lowercase,” “uppercase,” “reverse” and finally “length.” Obviously, since the names of these commands are extremely intuitive, I’m sure that you’ve already guessed that they’re used to uppercase, lowercase and reverse a given input string, in addition to calculating its length.

Nevertheless, it’s worthwhile to note here that all these simple string-related operations are performed internally by the interpreter by using the “loadString()” method that belongs to the “StringSaver” class. Simple to understand, right?

Okay, at this point I believe that you already understand how the previously-defined string interpreter class works. At this point I imagine you want to see for yourself how this class can be used in a concrete situation. Therefore, in the upcoming section I’m going to develop a simple example to demonstrate how the class in question can be capable of parsing the wealth of string commands that were discussed earlier.

To see how this practical example will be created, click on the link below and keep reading.

{mospagebreak title=Parsing string commands by using the StringInterpreter class}

If you’re anything like me, then you want to see how the previous string interpreter class can be used in the context of a hands-on example. Below I coded an easy-to-follow script, which demonstrates how different string commands are parsed by the corresponding interpreter, resulting in the manipulation of a specific input string.

Also, it’s worth clarifying that the following example assumes that a sample string has been saved previously to a default target file. Now, examine the corresponding code listing, which looks like this:

   // create ‘StringSaver’ object
   $stringSaver=new StringSaver();
   // save sample string to destination file
   // create ‘StringInterpreter’ object
   $stringInt=new StringInterpreter($stringSaver);
   // display lowercased input string
   echo $stringInt->interpret(‘lowercase’);

   /* displays the following:
   this is the default string

   // display uppercased input string
   echo $stringInt->interpret(‘uppercase’);

   displays the following:

   // display reversed input string
   echo $stringInt->interpret(‘reverse’);

   /* displays the following:
   gnirts tluafed eht si sihT

   // display length of input string
   echo ‘Number of characters of input string is the following :

   /* displays the following:
   Number of characters of input string is the following : 26
catch(Exception $e){
   echo $e->getMessage();

As shown above, the example first creates an instance of the “StringSaver” class, and uses its “saveString()” method to save a sample string to the default target file. Next, an interpreter object is spawned, and all the string commands accepted by this object are passed to the respective “interpreter()” method.

Of course, the purpose in doing this is simply to uppercase, lowercase and reverse the inputted string, something that is clearly demonstrated by the subsequent calls to the “interpreter()” method.

Finally, the example finishes displaying the number of characters corresponding to the aforementioned input string. Again, in this case the interpreter utilizes the predefined “length” command to perform this basic operation.

So far, so good. At this stage, and after studying the source code that corresponds to the previous practical example, you should have a better idea of how the interpreter pattern does its business. As you saw, the logic behind this pattern is extremely simple, and doesn’t differ too much from creating a conventional parsing class.

Final thoughts

It’s hard to believe, but we’ve come to the end of this second article of the series. In this tutorial, you learned how to implement the interpreter pattern in PHP 5 by using a bunch of simple classes, aimed at processing different input strings in a basic way.

Nonetheless, this is only the prologue for the next (and last) part of the series, since in it I’m going to demonstrate how this handy pattern can be used to develop a decent blog application. The experience sounds really promising and  educational. You won’t want to miss it!

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye