Posted: May 30th, 2008 | Author: tolleiv | Tags: behavioral, pattern, php, value object | Comments Off
This metaphor does not fit completely, and the “Money-Example” is omnipresent, but I really like the pattern and so that’s the story:
Let’s say you have your grannies recipe for a chocolate cookie and you want to keep this in mind, but also you like to somehow experiment with some new or different ingredients. Normally you just keep in mind what you changed and later you write down the new recipe. But from time to time you might want to compare the two recipes or maybe you want to make cookies with the new and the changed recipes. In this situation it’s really good to have both written down on paper.
In the world of OOP you could think of a solution using the Memento-Pattern but this doesn’t really fit the situation and it’s also some kind of overhead. That’s the reason why the Value Object is the pattern of my choice.
So let’s look at the recipes again – we want to add and remove ingredients without modifying the original recipe and we want to compare the resulting recipes. We don’t need to track a special identity of our recipes since we’re only “collecting” ingredients.
The idea of the Value Object is that every every method which somehow transforms the state of a object always returns a new object and the old object stays untouched. Whenever needed you should also implement a method to compare objects, I must concede that the common “Money Example” shows much better when that’s needed …
Another edge of this pattern in PHP is that you can use method-chaining to perform multiple actions within a single line of code. So just have a look at the example you will like it’s taste
class Recipe {
protected $ingredients;
public function __construct($ingred=”) {
$this->ingredients = implode(‘,’,array_unique(explode(‘,’,$ingred)));
}
public function addIncredient($ingred=”) {
return new Recipe($this->ingredients.‘,’.$ingred);
}
public function removeIncredien($ingred=”) {
return new Recipe(preg_replace(‘/,{0,1}’.$ingred.‘,{0,1}/’,”,$this->ingredients.‘,’));
}
public function printIncredients() {
echo str_replace(‘,’,‘
’,$this->ingredients);
}
public function equals(Recipe $recipe) {
return (strcmp($this->ingredients,$recipe->ingredients)===0)?true:false;
}
}
$granniesRecipe = new Recipe(‘flour,baking soda,sugar,salt,butter,vanilla,chocolate’);
$aNewRecipe = $granniesRecipe->addIncredient(‘lemon’);
$coconutRecipe = $granniesRecipe->removeIncredien(‘chocolate’)->addIncredient(‘coconut’);
// check if that worked:
echo ‘
Grannies Cookie Recipe – Incredients are:
’;
$granniesRecipe->printIncredients();
echo ‘
A new Cookie Recipe could look like:
’;
$aNewRecipe->printIncredients();
echo ‘
A coconut cookie would look like:
’;
$coconutRecipe->printIncredients();
The implementation is a bit odd, since it only collects the names of the ingredients but not the amount, but including the amounts of incredients would not change the concept and that’s why I left it out. I hope you got a idea how the pattern works – the main thing is that there’s no identity and that new objects are instantiated as soon as the state of the old one would change.
This metaphor does not fit completely, and the "Money-Example" is omnipresent, but I really like the pattern and so that's the story:
Let's say you have your grannies recipe for a chocolate cookie and you want to keep this in mind, but also you like to somehow experiment with some new or different ingredients. Normally ...
Posted: May 28th, 2008 | Author: tolleiv | Tags: creational, pattern, prototype | Comments Off
Imagine a cookie-oven which produces tasty cookies with chocolate crumbles. How do you ensure that the 1000th cookie still has the same taste as the first?
You might think that this is an easy task – just write down the recipe and follow the described steps…you know the result in real life – the 1000th cookie normally tasts like the 1st but you always had the “overhead” to read the recipe and go through the steps again and again.
In OOP it’s much easier to follow the recipe just instantiate a new Object and there you go… no matter if it’s the 1st or the 1000th – it’ll always taste look similar.
But the “recipe-overhead” is still there in a way and especially when you have larger objects whose construction is time-consuming you might want to somehow get rid of it. And that’s where a Prototype can help you out – you just create the first Cookie Object and then you use the handy magic method __clone to create new objects.
Instead of just using __clone the pattern suggests a class (some kind of a factory-class) so that you can also encapsulate the creation of the objects (and also possible adjustments you might want to make after the creation/clone).
So the example just shows a cookie-machine which makes use of the prototype-pattern to create new cookies (depending on the cookie you throw in before)… yummy
abstract class Cookie {
function __clone() { }
abstract public function printFlavor();
}
class CoconutCookie extends Cookie {
public function printFlavor() {
echo ‘Coconut Flavor<br/>’;
}
}
class ChocolateCookie extends Cookie {
public function printFlavor() {
echo ‘Chocolate Flavor<br/>’;
}
}
class CookieMachine {
protected $cookie;
public function __construct(Cookie $cookie) {
$this->cookie = $cookie;
}
public function makeCookie() {
return clone $this->cookie;
}
}
The client-code can look like this:
$coconutCookie = new CoconutCookie();
$coconutCookieMachine = new CookieMachine($coconutCookie);
$chocolateCookie = new ChocolateCookie();
$chocolateCookieMachine = new CookieMachine($chocolateCookie);
//while(true) {
for($i=0;$i<5;$i++) {
$coconutCookieMachine->makeCookie()->printFlavor();
$chocolateCookieMachine->makeCookie()->printFlavor();
}
Imagine a cookie-oven which produces tasty cookies with chocolate crumbles. How do you ensure that the 1000th cookie still has the same taste as the first?
You might think that this is an easy task - just write down the recipe and follow the described steps...you know the result in real life - the 1000th ...
Posted: May 15th, 2008 | Author: tolleiv | Tags: pattern, service, specification | 1 Comment »
Maybe sometimes the cookie tin is filled with all sorts of cookies and only some of them are what you’d like in this special moment. Often it’s very easy to specify which cookie you like, but sometimes your wishes are very complex, for example if you look for grannies special cookie with chocolate, coconut and vanilla crumbles. This could lead into a real crumby problem if you try to sort all the cookies and then select eat the right one.
In the world of OOP it’s often much harder to collect a few objects out of a large number of different objects, also combining different requirements isn’t easy and that’s where the specification pattern can help you out. It implements some basic operations to combine requirements (AND, OR, NOT) and the only thing a concrete specification for a concrete class has to do is to implement a method (isSatisfied()) which is able to determine whether a object meats a requirement or not.
I splitted the generic part of the script and the cookie-example. The first part just implements the methods which are needed for the combination and provides a abstract class which is extended by the specifications in the second part. As you see the specification is combined which normally encapsulates the retrieval of the objects ,for example from a database. ….just have a look it’s really easy to select the right cookie … yummy

interface Specification {
public function isSatisfiedBy($obj);
public function _and(Specification $spec);
public function _or(Specification $spec);
public function _not();
}
abstract class AbstractSpecification implements Specification {
public function isSatisfiedBy($obj) { }
public function _and(Specification $spec) {
return new AndSpecification($this, $spec);
}
public function _or(Specification $spec) {
return new OrSpecification($this, $spec);
}
public function _not() {
return new NotSpecification($this);
}
}
class AndSpecification extends AbstractSpecification {
private $spec1, $spec2;
public function __construct(Specification $spec1, Specification $spec2) {
$this->spec1 = $spec1;
$this->spec2 = $spec2;
}
public function isSatisfiedBy($obj) {
return $this->spec1->isSatisfiedBy($obj) && $this->spec2->isSatisfiedBy($obj);
}
}
class OrSpecification extends AbstractSpecification {
private $spec1, $spec2;
public function __construct(Specification $spec1, Specification $spec2) {
$this->spec1 = $spec1;
$this->spec2 = $spec2;
}
public function isSatisfiedBy($obj) {
return $this->spec1->isSatisfiedBy($obj) || $this->spec2->isSatisfiedBy($obj);
}
}
class NotSpecification extends AbstractSpecification {
private $spec;
public function __construct(Specification $spec) {
$this->spec = $spec;
}
public function isSatisfiedBy($obj) {
return !$this->spec->isSatisfiedBy($obj);
}
}
/**
* Cookie object just a container for the relevant data.
*
*/
class Cookie {
protected $name,$flavor,$size;
public function __construct($name=”,$flavor=‘chocolate’,$size=100) {
$this->name=$name;
$this->flavor = $flavor;
$this->size = abs($size); // avoid negative size
}
public function getName() { return $this->name; }
public function getFlavor() { return $this->flavor; }
public function getSize() { return $this->size; }
}
/**
* Cookie service delivers cookies, offers some ways to select specific types of cookies
*
*/
class CookieService {
protected $cookies = array();
/**
* Add a cookie to the collection
* name is used as identifier, thats not the best choice
* but it’s ok for the example
*
* @param Cookie $cookie
*/
public function add(Cookie $cookie) {
$this->cookies[$cookie->getName()]=$cookie;
}
/**
* Generic method to check which objects fit the spec
*
* @param Specification $spec
*/
private function filter(Specification $spec) {
$result=array();
reset($this->cookies);
foreach($this->cookies as $name=>$cookie) {
if($spec->isSatisfiedBy($cookie)) {
$result[]=$cookie;
}
}
return $result;
}
public function getLargeCookies() {
$spec = new SmallCookieSpecification();
$spec = $spec->_not();
return $this->filter($spec);
}
public function getSmallChocolateCookies() {
$spec = new SmallCookieSpecification();
$spec = $spec->_and(new ChocolateCookieSpecification());
return $this->filter($spec);
}
public function loadDummyData() {
$this->add(new Cookie(‘Granny\’s classic’,‘chocolate’,60));
$this->add(new Cookie(‘Modern Jumbo’,‘moca,chocolate’,180));
$this->add(new Cookie(‘Kitchen Sink’,‘macadamia,cranberrie’,90));
$this->add(new Cookie(‘Vanilla Cloud’,‘vanilla’,120));
$this->add(new Cookie(‘Chocolate chip’,‘coconut,chocolate’,160));
}
}
class SmallCookieSpecification extends AbstractSpecification {
public function isSatisfiedBy($obj) {
return $obj->getSize() < 100;
}
}
class ChocolateCookieSpecification extends AbstractSpecification {
public function isSatisfiedBy($obj) {
return stristr(strtolower($obj->getFlavor()),‘chocolate’) !== FALSE;
}
}
/**
* Client code
*/
$service = new CookieService();
$service->loadDummyData();
echo ‘
’;
var_dump($service->getLargeCookies());
var_dump($service->getSmallChocolateCookies());
echo ‘
’;
more information by E.Evans and M.Fowler
Maybe sometimes the cookie tin is filled with all sorts of cookies and only some of them are what you'd like in this special moment. Often it's very easy to specify which cookie you like, but sometimes your wishes are very complex, for example if you look for grannies special cookie with chocolate, coconut ...
Posted: May 13th, 2008 | Author: tolleiv | Tags: behavioral, memento, pattern | Comments Off
Let’s say you got a cookie from a repository your granny and you’re not sure if you like the new taste. Wouldn’t it be cool if you could just try it and revoke the operation first bite if you don’t like it?
In the world of OOP thats a easy job which can be handled by the so called memento pattern – you just save the inner state of the object within a memento object and revoke you actions whenever you like…
As UML the example looks like this:

Show PHP Source Code
class CookieMemento {
protected $flavor,$size;
public function __construct($flavor,$size=100) {
$this->flavor=$flavor;
$this->size=$size;
}
public function getMemento() {
return new CookieMemento($this->flavor,$this->size);
}
public function setMemento(CookieMemento $memento) {
$this->flavor=$memento->flavor;
$this->size=$memento->size;
}
}
class Cookie extends CookieMemento {
public function eat($reduceValue) {
$this->size-=($reduceValue>$this->size)?$this->size:$reduceValue;
}
public function printStatus() {
echo ‘This cookie is a ’.$this->flavor.‘ cookie which has a size of ’.$this->size.‘.
’;
}
}
class Client {
public function run() {
$theCookie = new Cookie(‘chocolate’,100);
$theMemento = $theCookie->getMemento();
echo $theCookie->printStatus();
$theCookie->eat(50);
echo $theCookie->printStatus();
$theCookie->eat(50);
echo $theCookie->printStatus();
echo ‘Hm I\’d like to eat it again …. *grin*
’;
$theCookie->setMemento($theMemento);
echo $theCookie->printStatus();
echo ‘ *biggrin* ’;
}
}
$cookieMonster = new Client();
$cookieMonster->run();
Let's say you got a cookie from a repository your granny and you're not sure if you like the new taste. Wouldn't it be cool if you could just try it and revoke the operation first bite if you don't like it?
In the world of OOP thats a easy job which can be handled ...
Posted: May 13th, 2008 | Author: tolleiv | Tags: pattern, prototype, structural | Comments Off
As the first pattern I’d like to introduce the decorator pattern – it’s one of the [GoF]- structural patterns. It enables to extend the functionality of a existing method by wrapping a so called decorator-object.
So maybe you already know the situation
, your granny is going to bake cookies and you think of how they gonna taste – so cookie is our main-object and the different additional spices and other options which refine the taste of the cookies are the decoration for it. The cookies, pardon main-objects, are fine without the decoration but they’re much better with and the best thing is that you’re able to combine the decorations… yummy
So that’s how this would look like more technically:

stract class Cookie {
protected $flavor;
public function __construct($flavor) {
$this->flavor=$flavor;
}
abstract public function descripeFlavor();
}
class GrannysCookie extends Cookie {
public function descripeFlavor() {
echo ‘
Granny baked a cookie which has a taste of ’;
echo $this->flavor;
}
}
abstract class CookieDecorator extends Cookie {
protected $cookie;
public function __construct(Cookie $cookie) {
$this->cookie = $cookie;
}
//abstract public function descripeFlavor();
}
class FreshCookieDecorator extends CookieDecorator {
public function descripeFlavor() {
$this->cookie->descripeFlavor();
echo ‘ which smells fresh from the oven’;
}
}
class CrumbleCookieDecorator extends CookieDecorator {
public function descripeFlavor() {
$this->cookie->descripeFlavor();
echo ‘ it has tasty crumbles ’;
}
}
$cookie = new GrannysCookie(‘chocolate’);
$cookie->descripeFlavor();
$crumbleCookie = new CrumbleCookieDecorator($cookie);
$crumbleCookie->descripeFlavor();
$freshCookie = new FreshCookieDecorator($cookie);
$freshCookie->descripeFlavor();
$freshAndCrumbledCookie = new FreshCookieDecorator($crumbleCookie);
$freshAndCrumbledCookie->descripeFlavor();
additional Information
As the first pattern I'd like to introduce the decorator pattern - it's one of the - structural patterns. It enables to extend the functionality of a existing method by wrapping a so called decorator-object.
So maybe you already know the situation ;) , your granny is going to bake cookies and you think ...