HomePHP Method Chaining: Adding More Methods to the Chain
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!