Design Pattern Principles for PHP: Program to an Interface; not an implementation

Principal's Principle

Principles in Design Patterns and OOP

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.

In Chapter 1 of the Gang of Four’s book, you will find an informative discussion of the concept. Also, online I found an interview with Erich Gamma that clearly explains what GoF meant by the principle of programming to an interface. Gamma points out,

Once you depend on interfaces only, you’re decoupled from the implementation. That means the implementation can vary, and that’s a healthy dependency relationship.

In this context, an interface includes not just the PHP structure keyword interface but also abstract classes. Gamma even points out,

One question is whether you should always use a [PHP] interface for that. An abstract class is good as well. In fact, an abstract class gives you more flexibility when it comes to evolution. You can add new behavior without breaking clients.

So what does this look like in PHP? You can “see” it more easily in Java, C#, ActionScirpt 3.0 or some other strongly typed language, but it’s pretty clear in PHP too. For example, in C#, you might have declare an instance like this:

private ISomething MyObject = new Something();

The ISomething reflects an interface or abstract class from which the Something() class is implemented or extended.

In PHP where you declare an instance you have no type reference, but you can program to the interface by declaring instances of classes derived from an interface. For example, the following code compares a very tightly coupled class with the output frozen into a literal and the execution locked into the constructor function with a class set that uses an interface and provides two methods for getting and setting values dynamically entered by the user.

<?php
//Case 1: Programming to an implementation
class Implementation
{
	private $pronouncement= "This is from an implementation.";
 
	function __construct() 
	{
            print $this->pronouncement . "<br/>";
   	}
}
 
$imp = new Implementation();
 
//Case 2: Programming to an interface
interface IFace
{
	public function setter($someString);
	public function getter();
}
//Implemented from IFace
class ConcreteFromInterface implements IFace
{
	private $stuff;
 
	public function setter($stuff)
	{
		$this->stuff=$stuff;
	}
 
	public function getter()
	{
		return $this->stuff;
	}
}
 
$inter=new ConcreteFromInterface();
$inter->setter("This is from an interface.");
print $inter->getter();
?>

Here’s what you’ll see:

This is from an implementation.
This is from an interface.

That example doesn’t exactly jump out at you and show how programming to an interface is helpful, but it’s a start. Both the direct implementation and the one through an interface encapsulate the property (a string in both cases) by using the private accessor, and so you’re not improving on encapsulation by using an interface. However, several different classes can use that same interface allowing you flexible implementation—you can implement the details of the interfaces methods any way you want as long as they have the same signature and all of the methods are implemented. In this way, your program is decoupled from the implementation.

Interface Data Typing with Type Hinting

In order to see a better example of decoupling we will use PHP5 type hinting. The class parameter in type hinting can be an interface; so, this should allow us to have different implementations of the same interface and everything should work as expected. The difference is that we’ve de-coupled the instance from the implementation. The following example illustrates this:

<?php
//Programming with Type Hinting
interface IFace
{
	public function setter($someString);
	public function getter();
}
 
// class ConcreteFromInterface
class ConcreteFromInterface implements IFace 
{
    private $stuff;
 
    public function setter($stuff)
    {
        $this->stuff=$stuff;
    }
    public function getter()
    {
        return $this->stuff ."<br \>";
    }
}
 
// class ConcreteFromInterface2
// Different implementation from 
// ConcreteFromInterface
class ConcreteFromInterface2 implements IFace 
{
    private $stuff;
 
    public function setter($stuff)
    {
	$this->stuff=$stuff;
    }
    public function getter()
    {
        return "Diffrent Implementation: " . $this->stuff;
    }
}
 
//Uses Interface IFace in Type hinting
class Program2Interface 
{
    public function __construct(IFace $concrete) 
    {
        print $concrete->getter($concrete->setter("Instance typed as IFace."));
    }
}
 
$concrete=new ConcreteFromInterface;
$useIFace=new Program2Interface($concrete);
$concrete=new ConcreteFromInterface2;
$useIFace=new Program2Interface($concrete);
?>

The output you will see is:

Instance typed as IFace.
Diffrent Implementation: Instance typed as IFace.

The $concrete instance is implemented with the same interface (IFace) but it has different implementations of the interface. However, because the type hinting points to the interface, it decouples the implementation and so the instance of the Program2Interface will accept either implementation.

By the way, if you’re going to be using type hinting to program to an interface, you can use the parent keyword as a shortcut for any super class. See the PHP Manual for more details on using type hinting with interfaces.

The following reasons seemed compelling enough to warrant additional discussion:

  • Includes dynamic binding
  • Closely tied to polymorphism
  • Built into Creation design patterns
  • Easy to begin programming for practical uses

Before starting, we’ll use the concept of an interface to refer to programs that use either abstract classes or interfaces. So, if you see a reference to an interface, it could well be an abstract class. It’s the concept of an interface that’s important; not the PHP interface statement.

Dynamic Binding, Polymorphism and Interfaces

Polymorphism is one of the pillars of OOP. This first principle of design patterns is tied into polymorphism. In order to follow the path from interfaces to polymorphism, we need to start with an operation’s signature. As you know, a signature is made up of the following:

  • operation’s name
  • objects it takes as parameters
  • return value

Figure 1 shows an example of a signature:

Figure 1: PHP Function Signature

In the signature of a strongly typed language, the return value is in the form of a return type in the same line as the name and parameters of an operation, but in a PHP signature, the return value needs to be found in the body of the operation. The point is that when using interfaces, all of the elements of a signature must be reflected in the implementation of the interface, including a returned value or no returned value.

In this context we can discuss interfaces as all of the operations in an object. For the most part, an object as used by GoF refers to a class and not an instance of a class as the term object is conventionally used. In referring the an object’s interface, whether it is a class or instantiated instance of a class, means all of the operations in the parents class. A parent class, as used here, refers to both abstract classes and interfaces.

Several different objects can have the same interface (primarily based on the superclass) but different implementations, and since the actual operation that is performed is dependent on both the request and receiving object’s name, the actual outcome occurs at run-time. Such an association between the a request and its operation at run-time is known as dynamic binding. The process of dynamic binding lets you substitute objects with identical interfaces at run-time. You probably know this process by another name, polymorphism.

Note: When looking at design patterns, you will notice that subclassing is through abstract classes. Rarely do you see any parent class to be a concrete one. All italicized text in a class diagram is either an interface or abstract class.

Design patterns help you set up interfaces and use polymorphism in organizing your program. The more you look at the different principles of OOP, the more you can see how these principles are maintained and presented in design patterns. Key are PHP pure interfaces and abstract classes. All operations in an interface are abstract, but an abstract class can defer some or all implementations to derived classes (subclasses.) Thus, the abstract class is more flexible than the pure interface, but both serve as interfaces

Reducing Implementation Dependencies

Gamma and his associates spell out two key benefits of manipulating objects solely in terms of the interface (of either pure interfaces or abstract classes).

1. Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.

2. Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface. (GoF, p. 18)

The whole purpose is to build functional structures but to keep them loose enough for change and reusability. Obviously you have to instantiate concrete classes, but by using the abstract class interface, (instead of the concrete classes’) you provide flexibility in the implementation. All design patterns in the Creational category [Factory Method, Abstract Factory, Prototype, Builder and Singleton] essentially force you to create your programs in a way that follows this principle.

Share

Copyright © 2010 William Sanders. All Rights Reserved.

5 Responses to “Design Pattern Principles for PHP: Program to an Interface; not an implementation”


  • Hey Bill,
    It’s great to see that you’re also into PHP. I have a spagettarian PHP site which needs serious refactoring.

    One of the problems I see in PHP is the lack of strict typing. We can use type hinting in PHP when passing parameters to functions but it seems that we cannot impose return types to them.

    Is there any way to do this?

    Thank you

    Curro

    Good luck with this new blog!

  • Hi Curro,

    I’ve been using type hinting when I can. I’m trying to finish up a post on PHP Strategy Design pattern. As you know I like to program without using conditional statements, and the Strategy pattern is one where you can avoid them. Once I’m finished, I should have an example that will have strategy classes for different SQL statement.

    Kindest regards,
    Bill

  • Thankyou soo much for this, i have read many articles on repository pattern etc
    Your article made it click in my brain

  • I read many articles about the first principle but couldn’t understand. Your explanation is much easier than I thought. I’ll read all your articles about design pattern principle. One question, What’s the different between a SOLID principle and design pattern principles? or design pattern principle followed the SOLID principles. Thanks.

  • Hi Bobby,

    Your question is a giant one and has many layers that I’m pretty sure were unintended. The group that put together the SOLID acronym represent the “Agile” movement begun in 2001 by Robert C. Martin and a small group of developers. It is a reaction against what they saw a rigid protocols for programming that emerged from both the academic and applied worlds. Ironically, some of those very protocols they advocated were from the same set of “rigid” rules they criticized. For example, Barbara Liskov of MIT, is the author of the Liskov Substitution Principle, discussed on this blog. Her principle (which is the ‘L’ in SOLID) fits in nicely with both the Agile movement’s approach as well as the more ordered principles found in what is considered the “Waterfall approach” that is far more ordered with tasks accomplished in a rigid sequence.

    Design patterns are not part of the debate between agile and waterfall approaches. The Gang of Four were addressing the issue of how OOP programs can be ordered to solve different kinds of typical programming problems. The important feature of design patterns is their flexibility, re-use capacity, loose binding, and the modular parts whereby different developers can work together independently within the same structure. The two key principles of design patterns are:

    Program to an interface; not an implementation

    and

    Favor object composition over class inheritance.

    Those two principles can be equally applied to both agile programming and the waterfall approach. So if you stick with design patterns when programming OOP, you’ll be welcomed in both camps!

    Kindest regards,
    Bill Sanders

Leave a Reply