What are Design Patterns
Design Patterns are simply defined solutions to common problems. Design patterns are not created by someone who sits in a room and decides to make a design pattern instead design patterns are proven solutions that are implemented over and over again through different projects. This re-use of the solution itself becomes a pattern. Don’t be intimidated by the fancy names given to design patterns, such as faade, singleton or observer, they are exactly that just fancy names given to repeatable solutions.
What Design Patterns Are NOT
- A design pattern is NOT a template rather a proposed solution that is not implementation specific. In other words you can take the same design pattern and implement it with any language, of course if the design pattern is an OO design pattern you need to implement it with an object-oriented language. More importantly the implementation itself may vary from project to project because of project restraints and requirements.
- A design pattern is NOT a framework, though depending on whom you speak to, a group of design patterns maybe considered as a design framework.
Why Use Design Patterns
Most PHP developers may first ask why use Design Patterns or why design in the first place. After all PHP is a scripting language usually used for simple web development, aren’t functions are good enough?
Yes this is probably true if you work alone on small projects. But you will find Design and Design Patterns are beneficial in regards of:
- Maintenance
- Documentation
- Readability
- Easy when developing in large development teams
- Developing Code to be used by other then yourself
With PHP becoming more and more mature, especially with PHP5 it is said it will be ready for the Enterprise world, see the following article http://www.theopenenterprise.com/shared/printableArticle?doc_id=TOE20021204S0001.
If this indeed is true then object-oriented development and design pattern skills are a definite asset to your resume. Most enterprise applications that succeed are because of the fact that a good methodology and development process is in place, and apart of that comes design and with design more then likely comes design patterns.
However there is a trade off with design patterns because it adds another layer/component of abstraction there maybe a loss in performance and efficiency. Granted this may not be noticeable on high-end servers, but could be problem on low-end servers.
Going off topic for moment, this is especially so when developing J2ME mobile applications, this would be prime example where coding like style would be more dominant then object-oriented coding purely for the fact that memory and heap size on mobile devices is limited.
Using Design Patterns with PHP
It is assumed you are familiar with object-oriented programming and more specifically object oriented programming with PHP, if not please refer to the DevArticle – Object Oriented Programming in PHP by Luis Argerich, http://www.devarticles.com/art/1/349.
There isn’t any point in redoing what other design pattern books completed already, nor is it possible to go over everything is to know about Design Patterns in a short article like this. For demonstration purposes I will briefly go over one of my favorite patterns in web development, validation using the Strategy Pattern.
Here is the UML diagram:
Diagram from phpPatterns.com by Harry Fuecks, visit phpPatterns for the full source code
For more detail explanation and complete source code for the validation using Strategy Pattern visit phpPatterns.com.
Possible code for a member sign up form would be:
if ( isset ($_POST['submit']) ) { if ($strlen($member) > 16) { // errormsg } if ($strlen($firstname) > 24) { } // - Check if firstname only contains charcters // - Check firstname doesn't contain reserved words // like root // - Check firstname doesn't contain unacceptable words // like swear words // - // // ETC }
This can get really complex and hard to maintain once you add in other required information such as country, postal code, address, primary phone, secondary phone, email, company name, etc.
As well it isn’t uncommon to have the same validation used in many places for example email would be validated during the signup process, login process (used as member name), forgot password, change email preference, newsletter signup and referral signup. As well some data may require the same type of validation such as first name, last name, member name and address. With the above code you might end up with a lot redundant code.
Of course, it is quite possible to use functions, and then you face the problem of making unique function names. Even with functions you will still find redundant code for things like error message handling other set of nested functions that make code maintenance more difficult.
To encapsulate this logic in a more efficient and maintainable approach would be to use the Strategy Pattern. Now with the Strategy Pattern in place the actually call to the validation classes are a lot more cleaner:
if ( $_POST['register'] ) { require_once('lib/Validator.php'); // Register the subclasses to use $v['u']=new ValidateUser($_POST['user']); $v['p']=new ValidatePassword($_POST['pass'],$_POST['conf']); $v['e']=new ValidateEmail($_POST['email']); $v['p']=new ValidateFirstName($_POST[pass'],$_POST[conf']); // Perform each validation // process error msg // .. continue program }
As you can see there are several benefits that come with using the Strategy Pattern for validation:
- Reuse error message handling.
- You can easily add or remove validation classes simply be adding or remove classes that inherit from Validator.
- Each child validation classes encapsulates its own set of requirements for validation which makes easier for any future maintenance and reduces the necessary regression testing.
- A common interface makes reusability of the same validation classes available in several parts of an application but with only one common area of maintenance.
Visit phpPatterns.com for the full source code and example.
What to Look Out For
Learning Process
Design Patterns and design are a learning process and is better approached after you have a fairly good grasp of object oriented development and the language your are using, in this case PHP. You will find a lot of the patterns are easier recognized rather then easier to learn after you’ve had experience coding. You will more then likely discover that you may have already come across the same type of problem more then once and was solved with the same type of solution.
You may have not known at the time you might have very well implemented a particular design pattern. For example, one of the first patterns you may find easy to use and understand is the Command Pattern because it replaces the commonly found code of large switch statements and/or large sets of if statements in your code.
PHP Object Model
PHP 4
As reminder the PHP object model is incomplete when compared to other OO languages, this may affect your implementation of design pattern if it requires the use of an OO characteristic PHP does not have, such as interfaces, private variables and private methods.
PHP5
The enhancements and changes in the up coming PHP 5 include changes in the object model. Rumor has it there will be support for such things as Abstract classes, interfaces and namespace.
Over Use and Over Design
Now that you understand design and more specifically the use of design patterns can be beneficial look out that you don’t fall into one or more these traps.
- Usually with design a modeling language and process is applied. Be careful not to over design making everything into a class and the use of a modeling language purely as documentation is something you should avoid as well.
- Try to avoid using a design that looks or seems cool; try understanding the gain and loss of using that particular design. As well just because design patterns are good doesn’t mean you have to use it.
- Try to avoid reusing the same pattern over and over again just because it is the one you know.
- Because PHP is not 100% object oriented and that the fact HTML page are static pages you may want to consider using more of a hybrid approach where you use design patterns where it makes sense.
For example, you have a website that produces content for web browsers, PDAs, cellular devices and WebTV. It would probably be in your best interest to use a MVC design pattern. Of course, there are other technology consideration that is out of this scope for this document such as XSL and Web Services. This Front view controller is maybe the only design pattern you use in this example and where the rest of your PHP code is coded procedurally.
Though I say this with discretion, most OO software designers would frown on what I just said and normally I would have to agree but as I mentioned before it really depends on what the software requirements are and the constraints you are faced with.
- You should consider prototyping your design to help you visualize the final outcome and prove that the design indeed works.
Not the Only Tool
If I have not indirectly stressed this earlier, I would like to make my point now like everything else we use in software development / engineering. OO and Design Patterns have its place, keep an open mind and use the relevant skills and technologies that satisfy the software requirements. Experience with using Design Patterns and knowing when to use them is simply an addition to your vast skills.
*Originally published at DevArticles.com
Click here to sign up for FREE tech. newsletters from Murdok!
Jason is a wireless and open source developer enthusiast who enjoys creating synergy and sharing knowledge in the software development world. To learn more about him visit his personal site at http://www.jasonlam604.com/