Completing a Sample String Processor with Method Chaining

In this third part of a 12-part series on method chaining, I complete the definition of the sample string processor class. This process will help reaffirm the concepts that you learned before regarding the definition and implementation of chainable methods in PHP 5.

Method chaining is a simple, yet powerful, programming approach that permits you to write classes whose methods can be easily linked with each other, thus building a modular and highly-compact API. Logically, as with other methodologies, chainable methods are not a proprietary feature of a particular programming language, but rather an approach that can be used for developing both client and server-side web applications, and desktop programs as well.

Fortunately, PHP developers like you also can take advantage of the benefits of using method chaining when working with the object-oriented paradigm. In this series of articles you’ll find numerous examples that not only will introduce you to the basics of this approach, but will show you how to use it in the context of real-world applications.

Naturally, if you already read the two preceding tutorials of the series, then at this stage you have a clearer idea of how to build chainable methods in PHP 5. In  those articles I developed a basic string processor class, which implemented some simple chainable methods for applying different filters to an incoming string.

In addition, it’s fair to recall that this sample class defined a factory method (also chainable), which allowed you to create a singleton of the string processor without having to call its constructor directly.

However, it’d be pretty instructive to expand the existing functionality of the mentioned class by adding a few additional methods to it, which will also be  completely chainable. In this third chapter of the series I’m going to finish developing this string processor class by incorporating into it some chainable methods that will be tasked with replacing characters in an inputted string with their equivalent HTML entities, and with for reversing their value as well.

Now, it’s time to continue creating more examples on using method chaining in PHP 5. Let’s jump in!

{mospagebreak title=Review: the string processor class}

Before I proceed to add a few more chainable methods to the string processor class to extend its existing functionality, it’d be really useful to recall its current signature, as defined in the previous article of the series.

That being said, here’s the definition of this sample class, which demonstrates in a nutshell how to code chainable methods in PHP 5:

class StringProcessor

{

private $str = ”;

private static $instance = NULL;

 

// factory method

// returns a singleton of string processor

// chainable

public static function factory($str)

{

if (self::$instance === NULL)

{

self::$instance = new StringProcessor($str);

}

return self::$instance;

}

 

// constructor

public function __construct($str = ‘This is a default string’)

{

$this->str= $str;

}

 

// trim white space from input string

// chainable

public function trim_space()

{

$this->str = trim($this->str);

return $this;

}

 

// uppercase input string

// chainable

public function str_upper()

{

$this->str = strtoupper($this->str);

return $this;

}

 

// lowercase input string

// chainable

public function str_lower()

{

$this->str = strtolower($this->str);

return $this;

}

 

// remove eventual HTML and PHP tags from input string

// chainable

public function remove_tags()

{

$this->str = strip_tags($this->str);

return $this;

}

 

// convert new lines to <br /> tags

// chainable

public function newline_br()

{

$this->str = nl2br($this->str);

return $this;

}

 

// convert new lines to paragraphs

// chainable

public function newline_par()

{

$this->str = ‘<p>’ . str_replace("n", ‘</p><p>’, $this->str) . ‘</p>';

return $this;

}

 

// get input string

public function get_string()

{

return $this->str;

}

}

Now that you’re hopefully familiar with the signature of the above “StringProcessor” class, here’s another code sample that shows how to use it to apply some of its filter to a trivial string. Take a look at it:

// process string by using factory method and chaining other multiple methods

echo StringProcessor::factory(‘ <strong>Hello ‘. "n" . ‘this is a simple example of method chaining in PHP</strong> ‘)->

trim_space()->

remove_tags()->

newline_par()->

get_string();

/*

displays the following

<p>Hello </p><p>this is a simple example of method chaining in PHP</p>

*/

As you can see, in this particular case I decided to utilize the class’s “factory()” method to process an example string, which not only can be chained to other methods very easily, but returns only a singleton of the class. Pretty illustrative and educational, right?

Well, at this point I’m sure you recalled the way that this simple class was coded, so it’s time to continue extending its current functionality. Thus, in accordance with the concepts deployed in the introduction, in the following section I’m going to add to the class a whole new chainable method that will be tasked with replacing certain characters of an incoming string with their corresponding HTML entities.

To learn more about how this specific method will be implemented, click on the link below and keep reading.

{mospagebreak title=Replacing characters of a string with HTML entities} 

One of the last chainable methods that I plan to add to the string processor class is one responsible for replacing certain characters of an incoming string with their correct HTML entities. As you may have guessed, this method will act as a proxy for the “htmlentities()” PHP native function. Its definition is shown by the code sample below:

class StringProcessor

{

private $str = ”;

private static $instance = NULL;

 

// factory method

// returns a singleton of string processor

// chainable

public static function factory($str)

{

if (self::$instance === NULL)

{

self::$instance = new StringProcessor($str);

}

return self::$instance;

}

 

// constructor

public function __construct($str = ‘This is a default string’)

{

$this->str= $str;

}

 

// trim white space from input string

// chainable

public function trim_space()

{

$this->str = trim($this->str);

return $this;

}

 

// uppercase input string

// chainable

public function str_upper()

{

$this->str = strtoupper($this->str);

return $this;

}

 

// lowercase input string

// chainable

public function str_lower()

{

$this->str = strtolower($this->str);

return $this;

}

 

// remove eventual HTML and PHP tags from input string

// chainable

public function remove_tags()

{

$this->str = strip_tags($this->str);

return $this;

}

 

// convert new lines to <br /> tags

// chainable

public function newline_br()

{

$this->str = nl2br($this->str);

return $this;

}

 

// convert new lines to paragraphs

// chainable

public function newline_par()

{

$this->str = ‘<p>’ . str_replace("n", ‘</p><p>’, $this->str) . ‘</p>';

return $this;

}

 

// parse special chars of input string

// chainable

public function parse_chars()

{

$this->str = htmlentities($this->str);

return $this;

}

 

// get input string

public function get_string()

{

return $this->str;

}

}

As depicted above, the “StringProcessor” class now implements a brand new chainable method called “parse_chars().” As I explained previously, this is a simple wrapper for the “htmlentities()” PHP function. Since this method can be easily chained to the existing ones, I’ve coded a simple example that shows how to use it in a concrete case. Here it is:

$strproc = new StringProcessor(‘ <strong>&Hello ‘. "n" . ‘this is a simple example of method chaining in PHP</strong> ‘);

// process string by chaining multiple methods

echo $strproc->trim_space()->

remove_tags()->

newline_par()->

parse_chars()->

get_string();

/* displays the following

&lt;p&gt;&amp;Hello &lt;/p&gt;&lt;p&gt;this is a simple example of method chaining in PHP&lt;/p&gt;

*/

From the previous example, it’s clear to see how the aforementioned “parse_chars()” method can be quickly chained to the others and replace some characters of the inputted string with their corresponding HTML entities. Simple to grasp, isn’t it?

Now that you understand how the “parse_chars()” method does its business, it’s time to finish building this sample string processor. With that idea in mind, in the last part of this tutorial I’m going to add to the class a couple of additional chainable methods for reversing the contents of a incoming string and for replacing certain characters with an arbitrary one.

To learn how these brand new methods will be defined, click on the link below and read the next few lines.

{mospagebreak title=Replacing and reversing characters of a literal}

As I stated in the section that you just read, the last two chainable methods that I’m going to add to the string processor class will be aimed at reversing and replacing their characters respectively.

That being said, here’s the complete signature of the sample class, this time including the aforementioned methods. Look at it, please:

class StringProcessor

{

private $str = ”;

private static $instance = NULL;

 

// factory method

// returns a singleton of string processor

// chainable

public static function factory($str)

{

if (self::$instance === NULL)

{

self::$instance = new StringProcessor($str);

}

return self::$instance;

}

 

// constructor

public function __construct($str = ‘This is a default string’)

{

$this->str= $str;

}

 

// trim white space from input string

// chainable

public function trim_space()

{

$this->str = trim($this->str);

return $this;

}

 

// uppercase input string

// chainable

public function str_upper()

{

$this->str = strtoupper($this->str);

return $this;

}

 

// lowercase input string

// chainable

public function str_lower()

{

$this->str = strtolower($this->str);

return $this;

}

 

// remove eventual HTML and PHP tags from input string

// chainable

public function remove_tags()

{

$this->str = strip_tags($this->str);

return $this;

}

 

// convert new lines to <br /> tags

// chainable

public function newline_br()

{

$this->str = nl2br($this->str);

return $this;

}

 

// convert new lines to paragraphs

// chainable

public function newline_par()

{

$this->str = ‘<p>’ . str_replace("n", ‘</p><p>’, $this->str) . ‘</p>';

return $this;

}

 

// parse special chars of input string

// chainable

public function parse_chars()

{

$this->str = htmlentities($this->str);

return $this;

}

 

// replace characters in input string

// chainable

public function replace_char($char = ‘ ‘)

{

$this->str = str_replace($char, ”, $this->str);

return $this;

}

 

// reverse input string

// chainable

public function reverse()

{

$this->str = strrev($this->str);

return $this;

}

 

// get input string

public function get_string()

{

return $this->str;

}

}

As you can see, by this time the class implants two additional methods, called “replace_char()” and “reverse().” Logically, the first one is aimed at replacing all of the occurrences of a character of a string with another one, while the second method simply will reverse its content.

Below I coded a couple of examples that show how to use these chainable methods. Here’s the first one:

$strproc = new StringProcessor(‘ <strong>Hello ‘. "n" . ‘this is a simple example of method chaining in PHP</strong> ‘);

// process string by chaining multiple methods

echo $strproc->trim_space()->

remove_tags()->

newline_par()->

replace_char(‘t’)->

get_string();

/*

displays the following

<p>Hello </p><p>his is a simple example of method chaining in PHP</p>

*/

And here’s the last code sample:

echo StringProcessor::factory(‘ <strong>Hello ‘. "n" . ‘this is a simple example of method chaining in PHP</strong> ‘)->

trim_space()->

remove_tags()->

reverse()->

get_string();

/* displays the following

PHP ni gniniahc dohtem fo elpmaxe elpmis a si siht olleH

*/

With these two final examples you should be armed with a solid foundation for coding your own chainable methods within your PHP 5 classes. As usual, feel free to edit and improve all of the code samples included in this tutorial, so you can more quickly grasp  the logic that stands behind creating truly chainable APIs.

Final thoughts

Over this third chapter of the series, I completed the definition of this sample string processor class, a process that hopefully helped to reaffirm the concepts that you learned before regarding the definition and implementation of chainable methods in PHP 5.

However, this class is just that: an example that can be used as a string helper in the real world. However, it’s also possible to apply the method chaining methodology in real applications as well, naturally. Therefore, in the next article I’m going to explain how to implement this approach for building a MySQL abstraction class.

Want to see how this will be done? Then don’t miss the upcoming tutorial!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort