Dec 07

Design patterns: compound patterns

Next chapter is quite complex. Literally complex. And I treat it as a last chapter of the book since it is a last chapter when you learn a new design pattern in a detailed way. And the last one of them is quite popular in many PHP frameworks. It is called MVC (Model-View-Controller). Maybe this is why it took me so long to write about it ;)

Frankly, I’ve been quite busy for last months and we released our new feature in Wikia: Wikia Maps. Additionally, I contributed to few other side projects, visited Velocity EU conference in Barcelona and just couldn’t find time to write about almost last chapter in the book I’ve been describing here.

Compound patterns

Enough of excuses! Let me continue describing the chapter. It is quite long one and I will split it into two posts. However, it does not mean the posts are going to be short. Let’s start with the first one.

There is quite artificial example at the beginning demonstrating how design patterns can work together. And this post will describe it. It is somehow back to the past — together with authors we are implementing a duck simulator! Almost the same one from beginning of the book.

First we implement a Quackable interface which is implemented by all other classes such as: MallardDuck, RedheadDuck, DuckCall and RubberDuck. Finally we implement the simulator itself and…

$ php app.php 
Duck Simulator
Quack
Quack
Kwak
Squeak

…done.

And here comes the first change: there are also geese around the place where ducks are. The simplest way is to implement a Goose class and make it quack. But geese can not quack! They can with a help of an adapter. We modify a little bit our simulator so it creates a GooseAdapter class instance. The adapter just overwrites the quack() method of Quackable interface which makes the simulator still work properly.

// GooseAdapter.class.php
class GooseAdapter implements Quackable {
    private $goose;

    public function __construct(Goose $goose) {
        $this->goose = $goose;
    }

    public function quack() {
        $this->goose->honk();
    }
}

Another change is a request from a quackologist to count all the quacks done by ducks. We create a decorator which gives ducks a new behavior — counting behavior. New QuackCounter class wraps Quackable objects and delegate the quack() call to the instance it is decorating but also increases the counter.

// QuackCounter.class.php
class QuackCounter implements Quackable {
    private $duck;
    private static $numberOfQuacks = 0;

    public function __construct(Quackable $duck) {
        $this->duck = $duck;
    }

    public function quack() {
        $this->duck->quack();
        static::$numberOfQuacks++;
    }

    public static function getQuacks() {
        return static::$numberOfQuacks;
    }
}

It provides a new static method to return the count. It is pretty straightforward and clean because we do not modify the Quackable class itself. The last step with this change is to wrap each Quackable object which we instantiate in a QuackCounter decorator and call QuackCounter::getQuacks() method at the end of our simulator.

$ php app.php 
Duck Simulator
Quack
Quack
Kwak
Squeak
Honk
The ducks quacked: 4 times

What the Quackologist notice is the inconvenience of decorating each instance. He is right and this is another change in our program we want to make. To hermitize the process of wrapping each Quackable object in a decorator we use a factory. The process is quite easy and we do not need to focus more on it (you can check it later in attached files).

The next requirement is to give our Quackologist possibility to manage a flock of ducks. Here comes the composite and itterator patterns for help. We create Flock class which implements our Quackable interface. It has add() method and quack() method.

// Flock.class.php
class Flock implements Quackable {
    private $quackers = [];
    
    public function add( Quackable $quacker ) {
        $this->quackers[] = $quacker;
    }

    public function quack() {
        $iterator = new ArrayIterator( $this->quackers );
        while( $iterator->valid() ) {
            $quacker = $iterator->current();
            $quacker->quack();
            $iterator->next();
        }
    }
}

The first one adds a Quackable objects into an array. The last one iterates through the objects and calls quack() method on them. In the simulator we just create flock of ducks and flock of mallards only and execute quack() on them.

Duck Simulator: with composite - flocks
Duck Simulator: whole flock simulation
Quack
Kwak
Squeak
Honk
Quack
Quack
Quack
Quack
Duck Simulator: mallard flock simulation
Quack
Quack
Quack
Quack
The ducks quacked: 11 times

The simulator works, so does the counting of ducks’ quacks.

Now, the Quackologist wants to be able to “track the individual ducks”. He wants to observe a duck which with Observer and QuackObservable interfaces is easy to achieve.

// Quackologist.class.php
class Quackologist implements Observer {
    public function update(QuackObservable $duck) {
        echo 'Quackologist: ' . get_class($duck) . ' just quacked.' . PHP_EOL;
    }
}

The Quackable interface extends QuackObservable, new Quackologist class implements Observer. After adding few more methods to our classes which implements Quackable interface and two lines to the simulator — it is done.

$ php app.php
Duck Simulator: with observer
Quack
Quackologist: RedheadDuck just quacked.
Kwak
Quackologist: DuckCall just quacked.
Squeak
Quackologist: RubberDuck just quacked.
Honk
Quackologist: GooseAdapter just quacked.
Quack
Quackologist: MallardDuck just quacked.
Quack
Quackologist: MallardDuck just quacked.
Quack
Quackologist: MallardDuck just quacked.
Quack
Quackologist: MallardDuck just quacked.
The ducks quacked: 7 times

The example, as I mentioned at the beginning of this post, is quite artificial. The authors tell us about it by themselves:

You should consider the DuckSimulator to be forced and artificial. You should never start out with the intention of using design patterns just for the sake of it.

The example was presented only to demonstrate how design patterns can work together. You only want to apply patterns when and where they make sense. You can download the Java code of the example “translated” into a PHP code.

The example was also a preludium to second part of the chapter: The King of Computed Patterns. This is the name given by authors to Model-View-Controller design pattern which we will get to in my next blog post.

Permanent link to this article: http://blog.lukaszewski.it/2014/12/07/design-patterns-compound-patterns/

Status update

Hi! I’ve been very busy since the beginning of the year. Hopefully I’ll write here something longer soon but today I only found few minutes to update the Design patterns: adapter post after reading an interesting article on Sitepoint.

Permanent link to this article: http://blog.lukaszewski.it/2014/04/09/small-update-in-the-adapter-post/

Jan 31

Design patterns: proxy

New 2014 year did not start easy for me in terms of describing new design pattern I have learnt by reading the book. The cause of it is next chapter I have read more than a month ago. It describes new proxy pattern but it describes it mostly in Java environment. However, it does not mean we use the pattern only in Java applications.

Book example

The history of cooperation with Mighty Gumball, Inc. continues. The CEO asks us for a better monitoring for the gumball machines. At first we add location property to GumballMachine class, assign a value to it via the constructor and added two getters: location getter and state getter. After these changes in existing class we create GumballMonitor class which is rather simple:

#
class GumballMonitor {
   private $machine;

   public function __construct( GumballMachine $machine ) {
      $this->machine = $machine;
   }

   public function report() {
      $r = '';
      $r .= "Gumball Machine:\t" . $this->machine->getLocation() . "\n";
      $r .= "Current inventory:\t" . $this->machine->getCount() . " gumballs\n";
      $r .= "Current state:\t\t" . $this->machine->getState() . "\n";
      echo $r;
   }
}

After few changes in app.php file the results are as follow:

$ php app.php 
Gumball Machine:        Seatle
Current inventory:      10 gumballs
Current state:          Machnine is waiting for quarter.

But once we show it to the CEO we learn the output is alright but he was not clear enough with us. He wants a remotely check the status of different machines (we are supposed to be Internet generation!). That changes a lot. However, not as much as we might think at the beginning. One of developers comes up with an idea of proxy and using Java RMI mechanism (java.rmi.* package). On next pages of the chapter you can read about it more. Basically, I do not think you need similar architecture in the world of web development and PHP ;) When I read it I thought that instead of RMI Stubs and RMI Skeletons we can just use HTTP protocols. Therefore, I will not describe the Java implementation here — it is in the book if you are interested :) Let’s jump to the proxy pattern definition:

The Proxy Pattern provides surrogate or placeholder for another object to control access to it.

Proxy pattern's diagram.

Proxy pattern’s diagram.

Later on we learn different kinds of proxy patterns:

  • remote proxy — manages interaction between a client and a remote object,
  • virtual proxy — controls access to an object that is expensive to instantiate,
  • firewall proxy — controls access to a set of network resources, protecting the subject from “bad” clients,
  • smart reference proxy — provides additional actions whenever a subject is referenced, such as counting the number of references to an object,
  • caching proxy — temporary storage for results of expensive operations; it can also allow multiple clients to share the results to reduce computation or network latency,
  • synchronization proxy — provides a safe access to a subject from multiple threads,
  • complexity hiding proxy — hides the complexity of and controls the access to a complex set of classes (this is sometimes called the Facade Proxy for obvious reasons); the complexity hiding proxy differs from facade pattern in that the proxy controls access, while the facade pattern just provides an alternative interface,
  • copy-on-write proxy — controls the copying of an object by deferring the copying of an object until it is required by a client; this is variant of virtual proxy.

Other examples

I read a lot on the Internat about proxy patterns used in Doctrine. A PHP object-relation mapping library. Once I read the pattern name it recalled me jQuery $.proxy() method we use a lot in our Wikia codebase. However, it is the same idea but set in the closoures’ world ;)

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: http://blog.lukaszewski.it/2014/01/31/design-patterns-proxy/

Dec 29

Design patterns: state

It’s about the time to put another design pattern post on my blog. This time I’ll write about state design pattern about which I read in the book. State pattern helps objects to control their behavior by changing their internal state. I also learnt it’s really similar to the first pattern in the book which was also mentioned by me on this blog: strategy pattern.

Book example

Imagine you’re working in B2B software company and Mighty Gumball, Inc. is asking you for help. They present you this diagram:

gumball machine flow

Mighty Gumball, Inc. gumball machine flow

and ask you to implement it in PHP. You can put everything in one class and implement it in this way:

#
class GumballMachine {
   const SOLD_OUT = 0;
   const NO_QUARTER = 1;
   const HAS_QUARTER = 2;
   const SOLD = 3;

   private $state = self::SOLD_OUT;
   private $count = 0;

   public function __construct( $count = 0 ) {
      $this->count = $count;

      if( $this->count > 0 ) {
         $this->state = self::NO_QUARTER;
      }
   }

   public function insertQuarter() {
      if( $this->state === self::HAS_QUARTER ) {
         echo "You can't insert another quarter\n";
      } else if( $this->state === self::NO_QUARTER ) {
         $this->state = self::HAS_QUARTER;
         echo "You inserted a quarter\n";
      } else if( $this->state === self::SOLD_OUT ) {
         echo "You can't insert a quarter. The machine is sold out.\n";
      } else if( $this->state === self::SOLD ) {
         echo "Please wait, we're already giving you a gumball\n";
      }
   }

   public function ejectQuarter() {
      if( $this->state === self::HAS_QUARTER ) {
         echo "Quarter returned.\n";
         $this->state = self::NO_QUARTER;
      } else if( $this->state === self::NO_QUARTER ) {
         echo "You haven't inserted a quarter.\n";
      } else if( $this->state === self::SOLD_OUT ) {
         echo "You can't eject, you haven't inserted a quarter yet.\n";
      } else if( $this->state === self::SOLD ) {
         echo "Sorry, you already turned the crank.\n";
      }
   }

   // more methods such as: turnCrank(), dispense(), __toString() and refill()
}

I shorten the example above because the rest of the methods were similar. The job we’ve done was really fast and software we created met all the requirements. It was tested and it just works. Our client is happy with the results. The job is done. Is it?

Mighty Gumball, Inc. did their own tests and they didn’t find any bugs. They are happy with our software and because it’s gone so smoothly they’d bring their machines to the next level and ask us about a small change. They want the machine to give a free gumball from time to time. Every 1 of 10 turns of the crank should give 2 gumballs. How would we implement it with our code? Well, we’d add new WINNER constant which will be new state of the machine and then… yes, then we’d have to modify all methods so they react correctly on the new WINNER state. It clearly tells us the previous design wasn’t good enough. We need to re-write the application at this point.

We should encapsulate what varies here which is the state of gumball machine. We’ll put each state’s behavior in its own class and then every state will just implement its own actions. The gumball machine will just delegate to the state object that represents the current state. This way we’ll favor composition over inheritance.

OK, let’s start with the State interface implementation:

#
interface State {
   public function insertQuarter();
   public function ejectQuarter();
   public function turnCrank();
   public function dispense();
}

It’s rather simple — we defined a method for each action done on the machine. How a concrete state class would look like? Here is an example:

#
class SoldState implements State {
   private $gumballMachine;

   public function __construct( $gumballMachine ) {
      $this->gumballMachine = $gumballMachine;
   }

   public function insertQuarter() {
      echo "Please wait, we're already giving you a gumball.\n";
   }

   public function ejectQuarter() {
      echo "Sorry, you already turned the crank.\n";
   }

   public function turnCrank() {
      echo "Turning twice doesn't get you another gumball!\n";
   }

   public function dispense() {
      $this->gumballMachine->releaseBall();
      if( $this->gumballMachine->getCount() > 0 ) {
         $this->gumballMachine->setState( 
            $this->gumballMachine->getNoQuarterState() 
         );
      } else {
         echo "Oops, out of gumballs!\n";
         $this->gumballMachine->setState( 
            $this->gumballMachine->getSoldOutState() 
         );
      }
   }
}

Implementation of other state classes is quite straight-forward. You can download all examples and you’ll notice that after implementing SoldOutState, NoQuarterState, HasQuarterState and SoldState classes, adding new methods and some changes in GumballMachine class we don’t have to touch the app.php file. It means that we made all the changes in code without changing API of GumballMachine class.

Implementing new feature such as 10% chance of getting two gumballs wasn’t hard as well. I created new WinnerState class which was really similar to SoldState and with few lines added to HasQuarterState the work was completed! A lot easier than adding another else-ifs.

Of course I could’ve implemented the new feature in already existing SoldState class but once again it was a trade-off I made. I decided to duplicate a little bit of code to keep SoldState class being responsible for only one thing. If I would’ve done it the other way imagine what could happen if the promotion ends? Or the stakes of the contest change?

OK, at the end let me introduce you the official definition of the state design pattern:

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.

State pattern's diagram.

State pattern’s diagram.

At the diagram the context is the class that can have a number of internal states (in example GumballMachine). The state interface defines a common interface for all concrete states; the states all implement the same interface, so they’re interchangeable. Whenever the request() is made on the context it is delegated to the state to handle. Each concrete state provides its own implementation for a request. In this way, when the context changes state, its behavior will change as well.

The diagram of state pattern is essentially the same as strategy pattern’s diagram. However, the patterns differ in their intent. I read in the book:

(…) With the state pattern, we have a set of behaviors encapsulated in state objects; at any time the context is delegating to one of those states. Over time, the current state changes across the set of state objects to reflect the internal state of the context, so the context’s behavior changes over time as well. The client usually knows very little, if anything, about the state objects.

With strategy, the client usually specifies the strategy object that the context is composed with. Now, while the pattern provides the flexibility to change the strategy object at runtime, often there is a strategy object that is most appropriate for a context object.

(…) In general, think of the strategy pattern as a flexible alternative to subclassing; if you use inheritance to define the behavior of a class, then you’re stuck with that behavior even if you need to change it. With strategy you can change the behavior by composing with a different object.

Think of the state pattern as an alternative to putting lots of conditionals in your context; by encapsulating the behaviors within state objects, you can simply change the state object in context to change its behavior.

If it doesn’t explain the difference good enough on the next pages in the book you can read a dialogue between strategy pattern and state pattern which explains it once again and helps you remember it ;)

Other examples

Except artificial book-oriented examples on the Internet I found one nice idea/example. Actually it’s a group of posts called PHP Game Making by Bill Sanders. In the second part from the group he demonstrates usage of state pattern in, known from The Big Bang Theory, R-P-S-L-S game. Other than that there are PHP implementations for different machines with buttons ;) Searching the web I also found two interesting pages which are generally about design patterns in PHP. Maybe you’ll find them interesting:

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: http://blog.lukaszewski.it/2013/12/29/design-patterns-state/

Nov 19

Design patterns: composite

While describing iterator pattern on previous post I mentioned it was a part of a bigger chapter in the Head First: Design Patterns book. The second design pattern described in the chapter is called composite. The composite pattern helps us create tree structures in our code. The book example this time is pretty straight-forward but the end of it shows the power of iterator and composite together.

Book example

We’re still with our merged restaurants. It’s easy to add more restaurants and merge their menus into one. We have our iterators to traverse through all menus and print them. But just when we thought it was safe we received a request we hadn’t expected: they want us to implement sub-menu.

The time has come to refactor all the code we’ve created so far! We’ve reached a level of complexity such that if we don’t rework the design now, we’re never going to have a design that can accommodate further acquisitions or sub-menus. Is the composite pattern the direction we should follow?

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

Composite pattern's diagram

Composite pattern

The Component defines an interface for all objects in the composition: both the composite and the leaf nodes. It may implement a default behavior for add(), remove(), getChild() and its operations. We’re going to implement MenuComponent in this place.
The Composite‘s role is to define behavior of the components having children and to store child components. In our implementation Menu class will become composite.
The Leaf defines the behavior for the elements in the composition. A leaf has no children. MenuItem class will be our leaf class.
Note that composites (Menu) and leaves (MenuItem) implement operations which may not make sense (for example implementing add() method in MenuItem class) so in that case an exception might be generated. That’s why we start with the MenuComponent class which is rather simple:

#
abstract class MenuComponent {
	
	// Composites' methods
	public function add( $menuComponent ) {
		throw new UnsupportedOperationException();
	}

	public function remove( $menuComponent ) {
		throw new UnsupportedOperationException();
	}

	public function getChild( $index ) {
		throw new UnsupportedOperationException();
	}

	// Leaves and composites' methods
	public function getName() {
		throw new UnsupportedOperationException();
	}

	public function getDescription() {
		throw new UnsupportedOperationException();
	}

	public function getPrice() {
		throw new UnsupportedOperationException();
	}

	public function isVegetarian() {
		throw new UnsupportedOperationException();
	}

	public function doPrint() {
		throw new UnsupportedOperationException();
	}
}

And then our new MenuItem class looks like this:

#
class MenuItem extends MenuComponent {
	// properties here ($name, $description, $vegetarian, $price)

	// __construct(), getName(), getDescription(), getPrice() 
	// and isVegetarian() are here...

	public function getListing() {
		$result = " " . $this->getName();
		
		if( $this->isVegetarian() ) {
			$result .= "(v)";
		}

		$result .= ", " . $this->getPrice();
		$result .= "     -- " . $this->getDescription() . "\n";

		return $result;
	}
}

The constructor and getters don’t change at all so I removed them from the listing above. The only changes are:
the class inherits now from MenuComponent and I added getListing() method which returns a string with all information connected to the menu item. All other methods inherited from MenuComponents will throw an exception if used on MenuItem instance.

So, the Menu class is slightly different:

#
class Menu extends MenuComponent {
	// properties here ($menuComponents, $name, $description)

	// __construct(), getName(), getDescription() are here...

	public function add( $menuComponent ) {
		$this->menuComponents[] = $menuComponent;
	}
	
	public function getChild( $index ) {
		return $this->menuComponents[ $index ];
	}

	public function getListing() {
		$result = "\n" . $this->getName();
		$result .= ", " . $this->getDescription() . "\n";
		$result .= "---------------------------------\n";

		$iterator = new ArrayIterator( $this->menuComponents );
		while( $iterator->valid() ) {
			$menuComponent = $iterator->current();
			$iterator->next();

			if( !is_null( $menuComponent ) ) {
				$result .= $menuComponent->getListing();
			}
		}

		return $result;
	}
}

It has less properties (and getters) but one of the properties is very important: $menuComponents. Within it Menu stores all its children. This class overwrites methods connected to children operations: add(), getChild(). We don’t want now the functionality of removing, so we just not overwrite the method here (it’ll throw an exception from MenuComponent class).

And this is the place (getListing() method of Menu class) where we use learnt earlier iterators. Thanks to the fact that we iterate through aggregates with Menu and MenuItem instances and they both implement print() method we’re sure the code is solid and does what we want — it prints all elements: menus and menus’ items.

Our client’s code (Waitress) class gets simplified as well:

#
class Waitress {
	private $allMenus;

	public function __construct( $allMenus ) {
		if( !$allMenus instanceof MenuComponent ) {
			throw new InvalidArgumentException();
		}

		$this->allMenus = $allMenus;
	}

	public function printMenu() {
		$menu = $this->allMenus->getListing();
		echo $menu;
	}
}

We don’t need the method which we pass menus’ iterator to. All we need is to recursively get all menus listed by calling getListing() on the top element and then print its results on the screen.

And this is the end of our refactoring. The chapter in the book continues with explaining why the design principle learnt in the same chapter wasn’t followed this time. Surely, the composite pattern manages hierarchy and it performs specific operations related to leaves. Of course this is a phenomenon which happens quite often in software development — classic case of tradeoff. We can say Signle Responsibility design principle is being trade for transparency. Transparency which makes the client treat leaves and composites uniformly. An example composite application can be as always downloaded here.

Other examples

Nice example of composite pattern is described by Craig Sefton on his blog. Craig describes how to use the pattern to be able to create not only one-level-flat lists from our real life.
Basically, that was my thought that composite is a great way to handle complex lists. And what are lists used for on the Internet? Menus! Probably there are lots of menu implementations using composite pattern. Maybe I’ll check it later :P

However, not only such simple components as menus can be handled by composites. Few years ago I learnt that Symfony 1.4 used decorator pattern for their views system. While looking for examples of composite pattern usages I’ve found very nice articles by Alejandro Gervasio. He describes there the mentioned way but also the other way: using composite design pattern to create view system! :)
Mentioning Symfony and more complex systems build with composite pattern, Hugo Hamon, presented practical usage of design patterns during this year PHP Benelux. You can see on his presentation composite used to build form builder.

I think these examples proves how useful the composite design pattern is. Sometimes, we have to make this tradeoff in favor of transparency.

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: http://blog.lukaszewski.it/2013/11/19/design-patterns-composite/

Oct 14

Design patterns: iterator

Next chapter in the book is the longest one. But I will split it into two posts because it’s about two design patterns. The first one’s name is: iterator and it was mentioned at least once before. I recall it while describing examples of adapter pattern usage. The iterator pattern, unlike other design patterns, helps us encapsulate an iteration. Let’s start with the book example.

Book example

Many previous examples were connected to cooking and this time it’s similar. We have two places which are going to be merged. Objectville Dinner and Objectville Pancake House agreed to have the same implementation of MenuItem:

#
class MenuItem {
	private $name;
	private $description;
	private $vegetarian;
	private $price;

	public function __construct( $name, $description, $vegetarian, $price ) {
		$this->name = $name;
		$this->description = $description;
		$this->vegetarian = $vegetarian;
		$this->price = $price;		
	}

	public function getName() {
		return $this->name;
	}

	public function getDescription() {
		return $this->description;
	}
	
	public function getPrice() {
		return $this->price;
	}
	
	public function isVegetarian() {
		return $this->vegetarian;
	}
}

But they have two different implementations of their menus and no one is willing to change it. The Java examples from the book may reflect the issue better but I’ll try to describe it with PHP code, anyway. Originally, PancakeHouseMenu uses ArrayList structure whereas DinnerMenu just a regular Array. There is only array type in PHP and my examples look a little bit different than the Java onces:

#
class DinnerMenu {
	private $menuItems;
	
	public function __construct() {
		$this->menuItems = new ArrayList();

		$this->addItem( "K&B's Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99 );
		$this->addItem( "Regular Pancake Breakfast", "Pancakes with fried eggs, sausage", false, 2.99 );
		$this->addItem( "Blueberry Pancakes", "Pancakes made with fresh blueberries", true, 3.49 );
		$this->addItem( "Waffles", "Waffles, with your choice of blueberries or strawberries", true, 3.59 );
	}

	private function addItem( $name, $description, $vegetarian, $price ) {
		$menuItem = new MenuItem( $name, $description, $vegetarian, $price );
		$this->menuItems->add( $menuItem );
	}

	public function getMenuItems() {
		return $this->menuItems;
	}

	// other methods here...
}
#
class PancakeHouseMenu {
	const MAX_ITEMS = 6;
	private $numberOfItems = 0;
	private $menuItems;

	public function __construct() {
		$this->menuItems = array();

		$this->addItem( "Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99 );
		$this->addItem( "BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99 );
		$this->addItem( "Soup of the day", "Soup of the day with a side of potato salad", false, 3.29 );
		$this->addItem( "Hotdog", "A hotdog, with saurkraut, relish, onions, topped with cheese", false, 3.05 );
	}

	private function addItem( $name, $description, $vegetarian, $price ) {
		$menuItem = new MenuItem( $name, $description, $vegetarian, $price );
		if( $this->numberOfItems >= static::MAX_ITEMS ) {
			echo "\nSorry, menu is full! Can't add item to menu.";
		} else {
			$this->menuItems[ $this->numberOfItems ] = $menuItem;
			$this->numberOfItems++;
		}
	}

	public function getMenuItems() {
		return $this->menuItems;
	}

	// other methods here...
}

I implemented simple ArrayList class in the PHP examples to make it easier to present the issue. And it exists in a client code which has to use the two menus — waitress ;) One of the waitress’ functions would be printing the menus. To achieve this it’ll have to create instances of PancakeHouseMenu and DinnerMenu and call on them getMenuItems() methods:

#
$pancakeHouseMenu = new PancakeHouseMenu();
$dinnerMenu = new DinnerMenu();

$breakfastItems = $pancakeHouseMenu->getMenuItems();
$lunchItems = $dinnerMenu->getMenuItems();

The results will be of different types so it’ll require the waitress (client) to use two loops:

#
for( $i = 0; $i < count( $breakfastItems ); $i++ ) {
	$item = $breakfastItems[$i];
	echo "\n" . $item->getName() . " ";
	echo "\n" . $item->getPrice() . " ";
	echo "\n" . $item->getDescription() . "\n";
}

for( $i = 0; $i < $lunchItems->size(); $i++ ) {
	$item = $lunchItems->get( $i );
	echo "\n" . $item->getName() . " ";
	echo "\n" . $item->getPrice() . " ";
	echo "\n" . $item->getDescription() . "\n";
}

Imagine there are more restaurants merged and for each of them we’ve got different menu and to display it we need to add more loops… How to avoid it? Well, as always let’s see what’s changing element here. It’s the iteration through different items. And we can encapsulate it with iterator design pattern which diagram and definition are presented below.

iterator design pattern's diagram

Iterator design pattern

The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

What we need to do is:

  1. Create iterators for our menus.
  2. Rework the menu with iterator.
  3. Fix up the waitress code.

Iterators for both menus are similar. The difference is in the implementation of next() and current() methods:

#
class DinnerMenuIterator implements Iterator {
// ...
	public function next() {
		$menuItem = $this->items->get( $this->position );

		if( !is_null( $menuItem ) ) {
			$this->position++;
			return $menuItem;
		} else {
			return null;
		}
	}

	public function current() {
		return $this->items->get( $this->position );
	}
// ...
}
#
class PancakeHouseMenuIterator implements Iterator {
// ...
	public function next() {
		if( isset( $this->items[ $this->position ] ) ) {
			$menuItem = $this->items[ $this->position ];
			$this->position++;
			return $menuItem;
		} else {
			return null;
		}
	}

	public function current() {
		return $this->items[ $this->position ];
	}
// ...
}

Changes in menu classes are simple: we add a getter which returns menu’s iterator and we remove getMenuItems() methods because we don’t need it anymore and what’s more important: we don’t want to expose internal implementation of a menu.

Our waitress function of printing menu is handled now by two methods: first one creates menu iterators’ instances and passes them to the second method which in one loops prints items for both menus.

#
class Waitress {
// ...
	public function printMenu() {
		$breakfastIterator = $this->pancakeHouseMenu->createIterator();
		$lunchIterator = $this->dinnerMenu->createIterator();

		echo "\n=== MENU ===\n";
		echo "\n=== BREAKFAST ===\n";
		$this->doPrintMenu( $breakfastIterator );

		echo "\n=== LUNCH ===\n";
		$this->doPrintMenu( $lunchIterator );
	}

	private function doPrintMenu( $iterator ) {
		while( ( $item = $iterator->next() ) instanceof MenuItem ) {
			echo "\n" . $item->getName() . " ";
			echo "\n" . $item->getPrice() . " ";
			echo "\n" . $item->getDescription() . "\n";
		}
	}
}

But the work done doesn’t reflect in 100% iterator pattern diagram. That’s because the client code depends on two classes where it could refer to each menu object using an interface rather than concrete class. Let’s create a Menu interface with createIterator() method. DinnerMenuIterator and PancakeHouseMenuIterator implement the new interface and reduce the dependency between Waitress and the concrete class.

Later we’re informed about another place being merged with our Pancake House and Dinner. The above change makes it easy to take it into account. The new place’s menu just have to implement Menu interface, make createIterator() method available and we can use it in our Waitress class. However, a small change there will make code easier to read and maintain. Let’s pass the menus’ objects to the Waitress class as an array. Then in printMenu() method just iterate through them and pass each’s iterator to doPrintMenu() method:

#
class Waitress {
	private $menus;

	public function __construct( $menus ) {
		$this->menus = $menus;
	}

	public function printMenu() {
		foreach( $this->menus as $menu ) {
			$menuIterator = $menu->createIterator();
			$this->doPrintMenu( $menuIterator );
		}
	}
// ...
}

Now, all the work is done and seems solid. We lost names of the menus but we could add the names to each menu. We also followed another design principle: single responsibility principle. It says that a class should have only one reason to change. If we would have left the classes responsibility of handling their aggregates and one more responsibility of iterating through aggregated elements then there would be two reasons to change. They would change if collections change and if the way we iterate through the collections changes. We know we want to avoid change in a class like the plague — modifying code provides all sorts of opportunities for problems to creep in. The above snippets are taken from full PHP example of iterator pattern usage I’ve written — feel free to take a look at it.

Other examples

Difference between types in Java and PHP was the hardest part to write this post’s code examples. Reading the part of the chapter about iterator design pattern was easy and with Java’s Array, ArrayList or Hashtable types it was even easier to understand how iterators help. Those built-in objects have their method’s such as iterator() which returns an iterator instances.

But PHP even though it doesn’t have so many collection types it has also quite cool built-in features. The list of built-in iterators is quite impressive. And unfortunately, I barely had chance to use them. Maybe it’s becauseof the feeling Stefan Froelich mentiones in his Sitepoint article about SPL Iterators. The overwhelming feeling when you see this impressive list of SPL iterators’ classes names.

However, once you start looking for examples of usage in Google you’ll find a lot of nice examples. You’ll find also quite markable words of one of the well known people from PHP world, founder of Sensio Labs:

(…)PHP also have a lot of awesome features; at least two of them are in my opinion largely underused: Iterators and Streams.Fabien Potencier

There is a simple example about using iterators and streams on his blog. Apropos Symfony there is a nice slide on Jack Smith’s presentation. The slide contains listing of iterators found in Symfony2. The presentation itself is really interesting because it shows several problems solved with iterators:

  • building unsorted list from multi-dimensional array (a web page menu in example),
  • removing recursively cache folders which are many levels deep in PHP,
  • listing directories’ content without version control folders (FilterIterator),
  • pagination done with iterators (!) (LimitIterator),

At the end one more presentation. This one was prepared by Dr Tarique Sani with examples of code which we used old-school loops versus new-school iterators ;)

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: http://blog.lukaszewski.it/2013/10/14/design-patterns-iterator/

Sep 22

Design patterns: template method

Chapter eight of the book is about template method pattern. It’s another way of encapsulation. The examples shows how to encapsulate piece of algorithms so the sub-classes can hook themselves right into computation any time they want. We learn a new design principle too!

Book example

First example is a real one from real life! ;) We implement code which makes a coffee or tea :) At the beginning we’re presented with code:

#
public class Coffee {
  
  public function prepareRecipe() {
    $this->boilWater();
    $this->brewCoffeeGrinds();
    $this->pourInCup();
    $this->addSugarAndMilk();    
  }

  private function boilWater() {
    echo "Boiling water\n";
  }
  
  private function brewCoffeeGrinds() {
    echo "Dripping coffee through filter\n";
  }

  private function pourInCup() {
    echo "Pouring into cup\n";
  }
  
  private function addSugarAndMilk() {
    echo "Adding sugar and milk\n";
  }
}
#
public class Tea {
  
  public function prepareRecipe() {
    $this->boilWater();
    $this->steepTeaBag();
    $this->pourInCup();
    $this->addLemon();    
  }

  private function boilWater() {
    echo "Boiling water\n";
  }
  
  private function steepTeaBag() {
    echo "Steeping the tea\n";
  }

  private function pourInCup() {
    echo "Pouring into cup\n";
  }
  
  private function addLemon() {
    echo "Adding lemon\n";
  }
}

Probably many of the readers are worried about the code duplication. And indeed, when we have code duplication it’s a signal we need to clean-up the design. We’re asked to draft possible class hierarchy. At first it’s probably made of three classes. The base class has prepareRecipe(), boilWater() and pourInCup() methods because they’re clearly common parts of code for Coffee and Tea classes and they don’t differ anyhow of each other. Two other classes are the ones presented above: Coffee and Tea. However with the new hierarchy contain less code and extend the brand new base class. They overwrite prepareRecipe() method and have two new methods each class (brewCoffeeGrinds(), addSugarAndMilk(), steepTeaBag() and addLemon()).

That was a move in the right direction but we can do better! Next step in the book is taking a look at the bigger picture. We abstracted boilWater() and pourInCup() methods but the ones left in sub-classes are practically the same! They just apply to different beverages. So, basically we can abstract prepareRecipe().
Brewing coffee grinds and steeping tea bag are, in general, brewing a beverage. And adding sugar, milk and lemon is nothing else than adding condiments the the beverage. At the end our parent class prepareRecipe() looks like this:

#
public function prepareRecipe() {
  $this->boilWater();
  $this->brew();
  $this->pourInCup();
  $this->addCondiments();
}

Then in the same class we define abstract methods brew() and addCondiments(), so the sub-classes have to implement them. We remove overwritten prepareRecipe() methods from Coffee and Tea classes and implement there only those two new methods. Here you can find final and working code.

As you suspect the prepareRecipe() method in our super class is nothing else than an example of template method design pattern usage. The book’s diagram and definition are as follows:

A template method pattern's diagram

A template method pattern’s diagram

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to sub-classes. Template Method let’s sub-classes redefine certain steps of an algorithm without changing the algorithm’s structure.

After learning the definition and diagram we read about pretty common practice of using hooks methods together with the template method pattern. Hooks are methods injected into our template method to make it more flexible/extensible. Going back to our coffee&tea example a hook could be added to prepareRecipe() method and depending on its result the addCondiments() method would be executed. New parent class code written in this way looks like:

#
abstract class CaffeineBeverageWithHook {

  public function prepareRecipe() {
    $this->boilWater();
    $this->brew();
    $this->pourInCup();
    
    if( $this->customerWantsCondiments() ) {
      $this->addCondiments();
    }
  }

// ...

  public function customerWantsCondiments() {
    return true;
  }
}

The sub-classes can overwrite the hook method and modify it but there isn’t “a must” to do so. In the code examples package, I put link to earlier, you’ll find working example of using hooks. I must admit that hooks in object-oriented way are even more useful in my eyes than hooks I’ve seen in some PHP code-bases.

After introduction to hooks we’re presented with another design principle: The Hollywood Principle. This time it’s pretty easy to remember: “Don’t call us, we’ll call you”. It helps us with preventing “dependency rot” in our code-base. Dependency rot happens when high-level class is depending on low-level classes which are depending on sideways components which are depending on low-level classes, and so on. When rot sets in, no one can easily tell the way a system is designed.
With the new principle we allow low-level components to hook themselves into a system, but high-level components determine when they are needed, and how. How does it work in our template method example? CaffeineBeverage has control over algorithm for the recipe, and calls on the sub-classes when they’re needed for an implementation of a method. This class is our high-level component which tells Coffee and Tea classes “don’t call us, we’ll call you”. The sub-classes never calls the abstract class directly. Clients of beverages will depend only on CaffeineBeverage abstraction rather than a concrete sub-classes. And this is how we reduce dependencies in the overall system.

After the new design principle authors show more examples of template method pattern implementations in Java. Not all of them depends on inheritance. There is an example with Comparable interface and compareTo() template method. The Java Arrays class is responsible for different arrays’ manipulation such as sorting. Arrays class implements all required steps of sorting but it let’s other classes decide on how elements are compared to each other.
The other two Java examples are examples of different classes and their hooks. JFrame class and its paint() hook method and Applet class with several hooks:

  • init() allows the applet to do whatever it wants to initialize the applet the first time,
  • start() allows the applet to do something when the applet is just about to be displayed on the web page,
  • stop() if the user goes to another page the stop() hook is used and the applet can do whatever it needs to do to stop its actions,
  • destroy(),
  • paint().

Other examples

Putting “php template method” in Google results in links to web pages which occurs the most often when you’re looking for examples of design patterns in PHP. Two of them describes the same abstract example of displaying books titles and authors. There is also well-known blog of author I’ve mentioned before: she had similar idea to mine — write about design patterns learn from Head First. Design patterns. It was a nice to see Sitepoint name within the results links (I really enjoy reading their articles). Example there describes how to use template method for rendering different jQuery sliders. It’s nice and more practical example than the ones described shortly before. One more nice example with step after step explanation is about implementing classes representing tweet text.

Separate paragraph needs to be written about hooks mentioned in the chapter. In all examples: books and the one I found on the Internet you read about them as method in the abstract class which can be overwritten by sub-classes. It’s clearly object-oriented and PHP wasn’t an object-oriented language. Therefore, you can find many PHP applications with the idea of hooks. In Wikia we use MediaWiki code and there is quite a long list of hooks you can hook into. WordPress since version 2.1 split hooks into two groups: filter and action hooks. Another blog application, Drupal, had its own hooks list but since version 8 they started using many Symfony’s components as well as its event listeners which allows to hook into Symfony application. Symfony, Zend, CodeIgniter and many other PHP frameworks uses different approaches to allow a developer to hook into their core code. But these hooks are a little bit different than hooks explained during learning template method design pattern. So let me stop at this point.

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: http://blog.lukaszewski.it/2013/09/22/design-patterns-template-method/

Aug 31

Design patterns: facade

The adapter pattern mentioned in previous post was only one of two design patterns mentioned in seventh chapter in the book. When you continue the reading you’ll find interesting discussion between a decorator and an adapter. It leads to the conclusion that both of these two design patterns seem to look similar on a paper but they are different in their intent. The end of this discussion as well as introduction to facade pattern is a simple table:

Pattern Intent
Decorator Converts one interface to another
Adapter Doesn’t alter the interface but adds responsibility
Facade Makes an interface simple

Book example

Before we learn the definition and schema of facade pattern we read about another real life example. It’s connected to the obsession some of us or our friends had: building a home theater. Usually it made of many of different components:

a home theater system class hierarchy

Many components of a home theater system

If you want to watch a movie there is few-steps procedure to set all the components of your home theater. Once you’ve done it you’re already tired. If you manage and finish the movie you have to repeat all the steps in reverse. Listening to a CD or a radio isn’t easier either. And things are getting more complex when you want to add new components. Facade pattern is the right design pattern to help you!

a home theater system with a facade class on the top

A home theater system with facade pattern used

The Facade Pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

An example application can be downloaded as usual. Feel free to play with it ;) However, it’s not the end of the chapter. The facade design pattern not only makes an interface simplier for a client but also helps us obligate to another OO principle. The principle of Least Knowledge as known as Law of Demeter: talk only to your immediate friends. It means when you’re designing an application, for any object, be careful of the number of classes it interacts with and also how it comes to interact with those classes. It prevents us from creating systems with a large number of classes coupled together so that changes in one part of the system cascade to other its parts. When you don’t apply this principle you’re probably creating fragile applications that will be costly to maintain and complex for others to understand. To make it easier you can take any object and then from any method in that object, the principle tells us that we should only invoke method that belong to:

  • the object itself,
  • objects pass in as a parameter to the method,
  • any object that methods creates or instantiates,
  • any components of the object (objects that are referenced by an instance variables).

The facade pattern is really helpful for us if we want to apply The Principle of Least Knowledge in our bigger systems. We can tell it just by looking at its diagram:

client and facade design pattern in terms of the principle of least knowledge

An example of how usage of facade pattern helps obey the principle of least knowledge

The client is coupled only with the facade which makes the client simple and flexible. Changes in any of subsystem’s classes don’t affect the client.

There weren’t any code snippets presented in the post content but as always you can download some code examples and take a look at them.

Other examples

Basically, there are as many real examples of facade pattern usage as complex systems. Asking Google for “php facade pattern example” or “php facade pattern real example” results with hundreds of thousands links. From simple array-string operations repeated on few pages, more real-life examples with simplifying books’ borrowing to more “backend-ish” solutions such as: creating template mechanism with caching to a Zend service for SlideShare. The last one is particularly interesting when there are more and more SOA around us ;)

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: http://blog.lukaszewski.it/2013/08/31/design-patterns-facade/

Status update

I’ve just updated my WordPress to 3.6 and found there are different formats options in the adding a new post view. This one is called “status”. Let’s see how it looks on the page… ;)

Permanent link to this article: http://blog.lukaszewski.it/2013/08/25/wordpress-update/

Jul 27

Design patterns: adapter

This time I’m writing about adapter pattern. This is an easy one to understand. Why? Because our world is full of real-life adapters. The authors of the book gives just this simple example about AC power adapter. We use it while traveling from Europe to United States because we want our laptops work there. So, we take our laptop’s plug-in connect it with an adapter and then plug it into US type wall outlet.

Book example

Code example in the book is quite unreal. Let’s go back to ducks’ example! ;) It’s a little bit far-fetched example but perfectly shows what adapter pattern does for us. We’ve got simplified version of Duck interfaces and classes:

#
interface Duck {
        public function quack();
	public function fly();
}
#
class MallardDuck implements Duck {
	public function quack() {
		echo "Quack! Quack! \n";
	}

	public function fly() {
		echo "I'm flying!\n";
	}
}

Those two structures are similar to the one mentioned in the first chapter in the book when strategy pattern was presented to us. But here is something fresh in our application:

#
interface Turkey {
	public function gobble();
	public function fly();
}
#
class WildTurkey implements Turkey {
	public function gobble() {
		echo "Gobble, gobble, gobble...\n";
	}

	public function fly() {
		echo "I'm flying a short distance.\n";
	}
}

Because of some strange reasons we can’t use Duck sub-classes anymore but we are allowed to use Turkey sub-classes instead. But instances of one and another class have different interfaces and to make it easy and possible to do we’re going to write an adapter class:

#
class TurkeyAdapter implements Duck {
	private $turkey;

	public function __construct( Turkey $turkey ) {
		$this->turkey = $turkey;
	}

	public function quack() {
		$this->turkey->gobble();
	}

	public function fly() {
		for( $i = 5; $i > 0; $i-- ) {
			$this->turkey->fly();
		}
	}
}

Now, we can use Turkey with Duck interface:

#
$wildTurkey = new WildTurkey();
$turkeyAdapter = new TurkeyAdapter( $wildTurkey );

$turkeyAdapter->quack();
$turkeyAdapter->fly();

After this a little bit unrealistic example authors of the book goes back to the AC power adapter example and explain us how a client use adapter pattern:

  1. The client makes a request to the adapter by calling a method on on it using the target interface.
  2. The adapter translates the request into one or more calls on the adaptee using the adaptee interface.
  3. The client receives the results of the call and never knows there is an adapter doing the translation.

Finally, we get to adapter pattern‘s definition:

The Adapter Pattern converts the interface of a class into another interface the client expects. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

Adapter pattern diagram from Head First: Design Patterns

Adapter pattern diagram from Head First: Design Patterns

The adapter’s introduction part in the chapter ends with short explanation about second type of adapters: class adapters. The solutions presented above were object adapter solutions. In programming languages where multiple inheritance is available you can create class adapter instead of object adapter. The only difference is that we use multiple inheritance instead of composition to translate one interface to another.

Then we have a really nice real java-life example ;) There were enumerators in some old Java version and they were replaced with iterators. The Enumeration interface looked like:

#
interface Enumeration {
	public function hasMoreElements();
	public function nextElement();
}

when Iterator:

#
interface JavaIterator {
	public function hasNext();
	public function next();
	public function remove();
}

What if you face legacy code that exposes the Enumeration interface, yet you’d like for your new code to use only iterators. You need to create an adapter!

#
class EnumerationIterator implements JavaIterator {
	private $enumeration;

	public function __construct( Enumeration $enumeration ) {
		$this->enumeration = $enumeration;
	}

	public function hasNext() {
		return $this->enumeration->hasMoreElements();
	}

	public function next() {
		return $this->enumeration->nextElement();
	}

	public function remove() {
		throw new UnsupportedOperationException( "remove() operation is not supported" );
	}
}

So, the answer for any legacy code that exposes an interface you’d like to replace with a better version is adapter pattern :)

The code example above as always can be downloaded from here. Notice that my PHP version of Iterator class was named JavaIterator that’s because I didn’t want to conflict with PHP built-in iterator interface.

Other examples

The examples in the book was quite unreal or strictly connected to Java world. But Google is your friend and there are lots of nice PHP examples. I found two twitter services examples on the first page of Google results presented to me. The first post has very nice introduction to adapter pattern. The second is just a nice example with using an adapter to translate more than one interface into target one. I also found that the lady with similar idea of mine wrote more about design patterns and you can find there the post about adapter pattern. She just stopped tagging them with “Head First Design Patterns” tag :)

Update (2014-04-09)
Today I read an article about interesting library called Flysystem. Once you visit the repository page on Github you’ll notice it’s nothing else as a group of adapters to different file systems. Pretty simple but very useful library. I encourage you to give it some time, read the article and play with the Flysystem itself ;)

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: http://blog.lukaszewski.it/2013/07/27/design-patterns-adapter/

Older posts «