Method Chaining: Adding More Methods to the Chain

In this second part of a 12-part series on method chaining, I explain how to extend the functionality of the string processor class by adding to it a few simple chainable methods. I conclude this part by defining a factory method within the string processor class.

Method chaining is a programming approach that permits you to chain multiple methods of a class in one single step, to perform several tasks in the context of a specified application.

Logically, this approach can be used equally with various programming languages, and PHP 5 certainly is no exception. Therefore, if you’re a PHP developer who wants to learn the basic concepts that surround the definition and implementation of chainable methods using PHP 5, then in this group of articles you’ll find the material that you’ve been looking for.

And now that you’ve been introduced to the primary goal of this article series, it’s time to review the topics that were covered in the last tutorial. In that article I proceeded to build a simple string processor class. It implemented a bunch of basic methods for performing some common tasks on an inputted string, such as removing unwanted tags from it, and upper casing and lower casing its characters.

Naturally, the most important thing to point out here is that despite the simplicity of the methods, they could be chained to each other, thus allowing us to use the class’ API in a much more compact and tight way.

Nonetheless, the functionality of this sample class can be enhanced through the codification of other chainable methods. What’s more, it’s possible to define a static factory method, also chainable, that allows you to create instances of the class without directly calling its constructor.

Bearing in mind all of these interesting possibilities, in this second part of the series I’m going to demonstrate how to accomplish these tasks in a truly friendly fashion, as usual by coding some comprehensive hands-on examples.

Now, let’s leave the preliminaries behind us and continue exploring the advantages of using method chaining in PHP 5. Let’s get going!

{mospagebreak title=Adding more methods to the string processor class}

As I said in the introduction, I’d like to extend the existing functionality of the string processor class coded in the previous article by adding some additional methods to it. This will show you how the method chaining approach can be used to accomplish this task in a simple manner.

So, with that idea in mind, below I listed an enhanced version of the string processor class. It includes a brand new chainable method called “newline_br()”, which is a wrapper for the native “nl2br()” native PHP function. Here it is:

class StringProcessor

{

private $str = ”;

private static $instance = NULL;

 

// 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;

}

// get input string

public function get_string()

{

return $this->str;

}

}

As I explained, now the above “StringProcessor” class implements a new chainable method named “newline_br()”, which is a simple proxy for the “nl2br()” PHP function. Of course, the most relevant aspect of this method is the fact that it’s completely chainable, so it can be used in conjunction with others to replace all of the new lines included in a given string by “<br /”> tags.

To demonstrate the functionality of this new chainable method, below I listed another code sample that shows how to work with it. Have a look at the  example:

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

// process string by chaining multiple methods

echo $strproc->trim_space()->

remove_tags()->

newline_br()->

get_string();

/*

displays the following

Hello <br />

this is a simple example of method chaining in PHP

*/

That was not rocket science, right? In the previous example the “newline_br()” method has been chained to some existing ones to replace all of the new line characters included in a sample string by “<br />” tags. The output generated by this particular example demonstrates how compact and tight the code looks when all of these methods are chained in one single step.

So far, so good. At this stage hopefully you understand how the “newline_br()” method does its business, meaning that it’s time to continue extending the functionality of the sample “StringProcessor” class by means of another chainable method.

In the next section I’m going to implement another method within the class, which will be responsible for replacing all of the new lines contained in a given string with paragraphs.

To learn more about how this method will be coded, click on the link below and read the next segment.

{mospagebreak title=Adding another chainable method to the class} 

One of the best things about using chainable methods is that it’s possible to add functionality to a determined class by progressively defining different links of this “chain,” which are tasked with performing well-differentiated tasks. That’s exactly the case with the method that I’m going to define in the next few lines. It will be charged with replacing all of the new lines contained in an inputted string with paragraphs. 

The signature of “StringProcessor” class, including this new chainable method called “newline_par()”, is shown below:

 

class StringProcessor

{

private $str = ”;

private static $instance = NULL;

 

// 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;

}

}

Undoubtedly, understanding how the “newline_par()” method works is a no-brainer process that can be tackled with minor effort. As I explained earlier, this chainable method will replace all of the new lines included in an input string with “<p>” tags, which makes it suitable for use as a typography helper.

However, the best way to grasp the functionality of this method is by means of a concrete example, which has been coded below. Look at it, please:

 

$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()->

get_string();

/*

displays the following

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

*/ 

As shown above, the string processor class is now capable or replacing new lines with paragraphs, aside from a few other useful tasks performed by the existing chainable methods that you learned before.

Of course, the actual beauty of this sample class rests in its ability to apply different filters to a given string by using a series of chainable methods that are simple to read and code. Period.

It’s quite probable that you’ve noticed that each time an instance of this class is created, it is accomplished by directly calling its constructor. This is a typical way to create objects, as you know, but unfortunately the constructor can’t be chained to other methods.

Nonetheless, it’s possible to overcome this small limitation by defining a factory method that not only returns instances of the class, but can be easily chained, too. So, as a fitting conclusion for this second article of the series, I’m going to explain how to create such a factory method.

Now, go ahead and read the last section. We’re almost finished!

{mospagebreak title=Defining a chainable factory method}

As I anticipated in the previous segment, it’s possible to define a factory method within the string processor class that returns instances of it, and that can also be chained to other methods.

To demonstrate how to create this chainable factory method, below I listed an enhanced version of the string processor class, which now includes the method in question. Here it is:

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;

}

}

If you pay attention to the current definition of the “StringProcessor” class, you’ll realize that it now includes a new method called “factory.” This method is not only completely chainable, but returns singletons of the class, in case you don’t want to deal with multiple instances.

Now that you’re aware of the functionality of this new factory method, here’s an example of how to use it in conjunction with others:

// 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>

*/

There you have it. As you can see, by directly calling the factory method of the string processor class, not only is it possible to chain multiple methods to filter a specified string, but there’s no need to deal explicitly with an instance of the class. The result of this process is a script whose code is extremely compact. Simple and effective, right?

Finally, with this last example I’m concluding  this tutorial on using chainable methods in PHP 5. As always, feel free to edit all of the code samples developed in it, so you can quicjkly grasp the underlying logic of this useful programming approach.

Final thoughts

In this second episode of the series, I explained how to extend the functionality of the string processor class by adding to it a few simple chainable methods, including one that creates instances of it as well.

In the next article, I’m going to complete the definition of this sample class by implementing some other chainable methods. These will come in handy for replacing specified characters with others in an inputted string, reversing its value and including HTML entities as well.

Don’t miss the upcoming part!

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

chat