HomePHP Page 2 - Working with Strings and the Composite Pattern in PHP 5
Handling strings of data - PHP
Are you a PHP developer who wants to improve your skills in pattern-based programming in PHP? If the answer to this question is an emphatic yes, then you should begin reading this article now! Welcome to the final part of the series “Implementing the composite pattern with PHP 5.” Comprised of two instructive tutorials, this series walks you through the basic concepts of this important design pattern, and shows you how to apply it with some educational examples.
In consonance with the objective of this tutorial, I’m going to build an abstract class. The class will define a generic model for creating some simple string processor objects.
Later on, based on the structure provided by this base class, I’m going to derive from it a pair of subclasses. Despite their different implementations, these subclasses will expose the same behavior when used within the context of a given PHP application.
As you may have noticed, this is exactly the intrinsic definition of the composite pattern. Having said that, please pay attention to the definition of the abstract class, shown below:
// define abstract 'StringProcessor' class abstract class StringProcessor{ // get information about selected string abstract public function getSelectedStringInfo( $singleStringProcessor); // get number of string processors abstract public function getNumberOfStringProcessors(); // add new string processor abstract public function addStringProcessor( $singleStringProcessor); }
As you can see, the above “StringProcessor” class presents a few generic methods that obviously will come in handy for performing some useful tasks. These tasks include getting information about a specific string of data, and counting and adding new string processor objects, which are inputted straight into the class via some of these methods.
However, don’t worry for the moment about how all these string processors will be defined, since I’ll be demonstrating how they look in the section to come.
All right, at this stage I simply created the abstract class that you saw before, but maybe you’re wondering…how does this fit into the schema imposed by the composite pattern?
Good question! Fortunately, the answer is quite simple. Since the composite pattern states clearly that one object or a group of objects will expose the same behavior across a given application, in the next few lines I’m going to create two subclasses from the base “StringProcessor.”
As you’ll see, these child classes will behave identically, in this way implementing the programmatic model dictated by the aforementioned pattern. Quite simple, isn’t it?
Okay, at this moment I’m pretty sure that you want to learn how these subclasses will be created, so click on the link that appears below and keep reading.