Posted: July 7th, 2008 | Author: tolleiv | Tags: behavioral, iterator, pattern, php, spl | Comments Off
Lot’s of people like to write down things into lists, so that they can go through that list later and check whether everything was fine. Normally every recipe has a list ~ there’s always a list of ingredients at the beginning of the recipe.
This short example shows how such a list can be processed in PHP. So why would you want to have something else than a array to hold your objects? – My example still uses a array to hold the objects (uni- or bidirectional lists would also be possible) but it adds a kind of a facade to the array so that the common managements-tasks are handled within the List-Object. Everything you need for this example is present in PHP since version 5.0. The basic steps you need to do is to provide a “Object” and an “ObjectList” which implements the native “Iterator” interface and then you’re able to have very handy lists 
class Incredient {
public $name,$amount;
public function __construct($name,$amount) {
$this->name = $name;
$this->amount = $amount;
}
}
class Recipe implements Iterator {
public $title;
private $ingredients;
public function __construct ($title) {
$this->title = $title;
}
public function addIncredient(Incredient $in) {
$this->ingredients[] = $in;
}
public function current () { return current ($this->ingredients); }
public function key () { return key($this->ingredients); }
public function valid () { return current ($this->ingredients); }
public function rewind () { return reset ($this->ingredients); }
public function next () { return next ($this->ingredients); }
}
$cookieRecipe = new Recipe(“Chocolate Cookie”);
$cookieRecipe->addIncredient(new Incredient(‘Flour’,’2.5 cups’));
$cookieRecipe->addIncredient(new Incredient(‘Baking soda’,’1 teaspoon’));
$cookieRecipe->addIncredient(new Incredient(‘Salt’,’0.5 teaspoon’));
$cookieRecipe->addIncredient(new Incredient(‘Butter’,’1 cup’));
$cookieRecipe->addIncredient(new Incredient(‘Sugar’,’1 cup’));
$cookieRecipe->addIncredient(new Incredient(‘Brown Sugar’,’0.5 cup’));
$cookieRecipe->addIncredient(new Incredient(‘Vanilla extract’,’1 teaspoon’));
$cookieRecipe->addIncredient(new Incredient(‘Egg’,’1-2′));
$cookieRecipe->addIncredient(new Incredient(‘Chocolate chips’,’2 cups’));
// process recipe:
foreach($cookieRecipe as $inc) {
echo $inc->name.“ => ”.$inc->amount.“<br/>”;
}
As you see it’s pretty easy to have lists of objects in PHP. You might also think that always creating to some list-object over and over again is very odd and you’re right. For the most common tasks like iterating through arrays, directory-lists and a few more task you can use objects which are shipped with the Standard PHP Library ,which is also part of PHP since version 5 and mandatory in 5.3. So the example shown above could also look like this:
$recipe = array();
$recipe[] = new Incredient(‘Flour’,’2.5 cups’);
$recipe[] = new Incredient(‘Baking soda’,’1 teaspoon’);
$recipe[] = new Incredient(‘Salt’,’0.5 teaspoon’);
$recipe[] = new Incredient(‘Butter’,’1 cup’);
$recipe[] = new Incredient(‘Sugar’,’1 cup’);
$recipe[] = new Incredient(‘Brown Sugar’,’0.5 cup’);
$recipe[] = new Incredient(‘Vanilla extract’,’1 teaspoon’);
$recipe[] = new Incredient(‘Egg’,’1-2′);
$recipe[] = new Incredient(‘Chocolate chips’,’2 cups’);
$recipeIncObj = new ArrayObject($recipe);
$ingredientsIt = $recipeIncObj->getIterator();
foreach($ingredientsIt as $inc) {
echo $inc->name.“ => ”.$inc->amount.“<br/>”;
}
As I said at the beginning, there are lots of situations where you might want to have a list for something and if you store that list in PHP the Iterator-pattern can keep your code clean and tasty
Lot's of people like to write down things into lists, so that they can go through that list later and check whether everything was fine. Normally every recipe has a list ~ there's always a list of ingredients at the beginning of the recipe.
This short example shows how such a list can be processed in PHP. So why would you want to have something else than a array to hold your objects? - My example still uses a array to hold the objects (uni- or bidirectional lists would also be possible) but it adds a kind of a facade to the array so that the common managements-tasks are handled within the List-Object. Everything you need for this example is present in PHP since version 5.0. The basic steps you need to do is to provide a "Object" and an "ObjectList" which implements the native "Iterator" interface and then you're able to have very handy lists :)
class Incredient {
public $name,$amount;
public function __construct($name,$amount) {
$this->name = $name;
$this->amount = $amount;
}
}
clas
Posted: July 1st, 2008 | Author: tolleiv | Tags: behavioral, null, pattern, php | 1 Comment »
Very often you create a object with a factory and before you really start using it, you check if your factory really created a object or returned NULL. Or maybe you have a method where a object is passed in and in this situation you’ll have to do this check also.
Instead of typing the “if(object == null)” phrase again and again, you could use the Null-Object pattern, you’ll see that this can make some situations much clearer.
Basically Null-Object ensures that the client always receives a valid object for it’s interaction, so that there’s no need to do the check shown above again and again. This happens since your concrete Null-Object just shares the interface, or inherits from the same class as it’s effective counterpart, but it’s implementation just leaves out any effectiveness.
So a code-example could look like this:
class CookieFactory {
public function makeInstance() {
if(date(‘l’)==‘Monday’) return new NullCookie();
return new RealCookie();
}
}
interface iCookie {
function getCalories();
}
class RealCookie implements iCookie {
protected $calories=250;
public function getCalories() {
return $this->calories;
}
}
class NullCookie implements iCookie {
public function getCalories() {
return 0;
}
}
I think you can imagine what happens when you make use of the CookieFactory - diet on monday
There’re also some disadvantages, your clients normally don’t have a chance to react that there’s something special happening, also the clients must “share” the same expectation what “do nothing” means, the number of required Null-Objects might be very large and unhandy and the Null-Object shares a very deep knowledge with the real one, so that it might be a large effort to create it if the real object is complex too.
I’m so glad that today is tuesday
Very often you create a object with a factory and before you really start using it, you check if your factory really created a object or returned NULL. Or maybe you have a method where a object is passed in and in this situation you'll have to do this check also.
Instead of typing the "if(object == null)" phrase again and again, you could use the Null-Object pattern, you'll see that this can make some situations much clearer.
Basically Null-Object ensures that the client always receives a valid object for it's interaction, so that there's no need to do the check shown above again and again. This happens since your concrete Null-Object just shares the interface, or inherits from the same class as it's effective counterpart, but it's implementation just leaves out any effectiveness.
So a code-example could look like this:
class CookieFactory {
public function makeInstance() {
if(date('l')=='Monday') return new NullCookie();
return new RealCookie();
}
}
interface iCookie {
function getCal
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 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
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 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->si