One of the things we’ve learned from our discussions of design patterns and OOP is that very few want to discuss principles. Put in a piece of code and there’ll be plenty of comments on how to tweak the code, but when we write about principles, we only get a few comments—if we get any at all.
We wish the opposite were true, and readers would gather up some code to illustrate their conception of a principle at work. We’re hoping that because PHP is a dynamic language (aka: weakly typed) there’ll be plenty of discussion of principles that were apparently created for strongly typed languages like Java, C# and ActionScript 3.0. In order to signal that a post is about a principle we’ve included an image of our favorite principal, Principal Seymore Skinner of the Simpsons. When you see Skinner, think OOP/Design Pattern Principle and I’ve got something to say about that!
The first principle of design patterns is,
Program to an interface, not an implementation
Simply put, the Gang of Four urges programmers to declare variables only to abstract classes and interfaces and not concrete implementations. You never want to type your instance as a concrete class derived from an interface or abstract class—only to the interface.
For any red-blooded PHP programmer, this may sound heretical because one does not declare types with either variables or functions. (Type hinting may do something like that, but more on it later.) However, after only a little reflection, we realize that PHP can indeed program to the interface by declaring variables (properties) and functions (methods) through classes that implement interfaces or extend abstract classes.
Continue reading ‘Design Pattern Principles for PHP: Program to an Interface; not an implementation’
Recent Comments