As I stated in the introduction, the best way to understand how to chain methods of a class is by way of a basic example. Thus, with that idea in mind, I'm going to build a simple string processor class that will be tasked with applying different filters to an input string, such as trimming white spaces, removing tags, capitalizing and lowercasing its characters and so forth. However, and here's where method chaining comes in, the methods responsible for performing these tasks will be completely "chainable." Take a look at the initial definition for the aforementioned string processor class: // define 'StringProcessor' class 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; }
// get input string public function get_string() { return $this->str; } } As you can see, the above "StringProcessor" class looks extremely simple. It implements only three basic methods, apart from the constructor. The first one trims white space from an inputted string; the second one is responsible for capitalizing its characters, and the last one returns the string in question. As I said before, the logic of these methods is very easy to grasp. If you take a closer look at the first two, though, you'll see that they return an instance of the class to calling code. What does this mean in simple terms? Well, they can be chained and used together to process an input string. The best way to understand how these methods can be chained is by means of an example, so I coded it for you. Pay close attention:
$strproc = new StringProcessor(' Hello, this is a simple example of method chaining in PHP '); // process string by chaining 3 methods echo $strproc->trim_space()-> str_upper()-> get_string(); /* displays the following HELLO, THIS IS A SIMPLE EXAMPLE OF METHOD CHAINING IN PHP */ See how simple it is to chain the three methods implemented by the "StringProcessor" class to parse a trivial string? I guess you do. In this particular case, first the inputted string is trimmed, then it is upper cased, and finally it is echoed to the browser. Of course, I'm not sating that you have to code all of your PHP classes using method chaining, but the above example shows in a nutshell how compact the whole code looks. So far, so good. Now that you hopefully have a clearer idea of the logic that stands behinds utilizing chainable methods, it's time to continue adding more methods to the "StringProcessor" class, which logically will be chainable as well. To see how these brand new methods will be implemented, click on the link below and read the following section.
blog comments powered by Disqus |
|
|
|
|
|
|
|