Jun 30

Design patterns: command

This month I’m writting about command pattern. This is another design pattern which helps us decoupling some actions in similar way to strategy pattern. To be more specific it makes us able to encapsulate method invocation. The last word made me thinking of PHP unit tests while reading — but I’ll get back to it at the end of this post.

Book examples

Similar to strategy pattern and other patterns described in the book we face a real life problem. We’re asked to create a system to a remote controller which will be able to operate on several different devices. The offer includes a CD with driver classes to these different devices. You can download its PHP versions together with examples of code I’ve written.

However, it takes few pages to get to the clue. That’s because this time authors wants us to get familiar with a bunch of new names: client, command, invoker and reciver. These four roles are described at the begining of the chapter as particular roles in a dinnery. In this way we’re being introduced to command pattern before switch to the main task: a remote controller application. A dinnery costumer makes an order, she tells it the waitress who then passes it to the cook who creates the final product. The costumer is a client in the new terminology. The order is a command, the waitress is an invoker and the cook is a reciver. After this short introduction we can move on with implementing a command pattern in the remote controller application.

After few funny texts, ilustrations and exercies together with authors we create first command object. We start of creating a command interface which is reather simple:

#
interface Command {
    public function execute();
}

The first command object is an object with gives us a possibility to turn on a light:

#
class LightOnCommand implements Command {
    private $light;

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

    public function execute() {
        $this->light->on();    
    }
}

Let’s create a simple class representing remote control (with only one slot and button) and its test application, so we can see how everything works:

#
class SimpleRemoteControl {
    private Command $slot;
    
    public function setCommand( $command ) {
        $this->slot = $command;        
    }

    public function buttonWasPressed() {
        $this->slot->execute();
    }
}
# 
$remote = new SimpleRemoteControl();
$light = new Light();
$lightOn = new LightOnCommand($light);
$remote->setCommand($lightOn);
$remote->buttonWasPressed();

It works. The Light::on() method simply prints on screen Light is ON message. After this simple coding we’re asked in an excercise to implement GarageDoorOpenCommand. It’s not so hard, isn’t it? After implementing it we can just switch the command in our application:

# 
$remote = new SimpleRemoteControl();

$light = new Light();
$lightOn = new LightOnCommand($light);

$garageDoor = new GarageDoor();
$garageOpen = new GarageDoorOpenCommand($garageDoor);

$remote->setCommand($lightOn);
$remote->buttonWasPressed();

$remote->setCommand($garageOpen);
$remote->buttonWasPressed();

Let’s move on, the authors finaly presents us the definition of command pattern:

The Command Pattern encapsulates a request as an object, therby letting you parameterize other objects with different requests, queue or log requests and supports undoable operations.

Command pattern diagram from Head First: Design Patterns

Command pattern diagram from Head First: Design Patterns

At this point we read about the implementation of main task. We implement six more command objects:

  • CeilingFanOnCommand,
  • StereoOnWithCdCommand,
  • LightOffCommand,
  • CeilingFanOffCommand,
  • GarageDoorClose,
  • StereoOffCommand,

We add RemoteControl class:

# 
class RemoteControl {
    const BUTTONS_NO = 7;
    private $onCommands;
    private $offComands;

    public function __construct() {
        $noCommand = new NoCommand();
        for( $i = 0; $i < = self::BUTTONS_NO; $i++ ) {
            $this->onCommands[$i] = $noCommand;
            $this->offCommands[$i] = $noCommand;
        }
    }

    public function setCommand($slotNo, $onCommand, $offCommand) {
        $this->onCommands[$slotNo] = $onCommand;
        $this->offCommands[$slotNo] = $offCommand;
    }

    public function onButtonPressed($slotNo) {
        $this->onCommands[$stotNo]->execute();
    }

    public function offButtonPressed($slotNo) {
        $this->offCommands[$stotNo]->execute();
    }

    public function __toString() {
        $result = "\n --- Remote Control -- \n";
        foreach($this->onCommands as $slotNo => $command) {
            $result .= "slot[" . $slotNo . "]" . get_class($this->onCommands[$slotNo]) . "\t" . get_class($this->offCommands[$slotNo]) . "\n";
        }

        return $result;
    }
}

And change a little bit our application code:

# 
$remoteControl = new RemoteControl();

// create all devices instances
$livingRoomLight = new Light('Living room');
$kitchenLight = new Light('Kitchen');
$ceilingFan = new CeillingFan('Living room');
$garageDoor = new GarageDoor();
$stereo = new Stereo('Living room');

// create light commands
$livingRoomLightOn = new LightOnCommand($livingRoomLight);
$livingRoomLightOff = new LightOffCommand($livingRoomLight);
$kitchenLightOn = new LightOnCommand($kitchenLight);
$kitchenLightOff = new LightOffCommand($kitchenLight);

// create ceiling commands
$ceilingFanOn = new CeillingFanOnCommand($ceilingFan);
$ceilingFanOff = new CeillingFanOffCommand($ceilingFan);

// create garage door commands
$garageDoorUp = new GarageDoorOpenCommand($garageDoor);
$garageDoorDown = new GarageDoorCloseCommand($garageDoor);

// create stereo commands
$stereoOnWithCd = new StereoOnWithCdCommand($stereo);
$stereOff = new StereoOffCommand($stereo);

// set functions of the remote control
$remoteControl->setCommand(0, $livingRoomLightOn, $livingRoomLightOff);
$remoteControl->setCommand(1, $kitchenLightOn, $kitchenLightOff);
$remoteControl->setCommand(2, $ceilingFanOn, $ceilingFanOff);
$remoteControl->setCommand(3, $stereoOnWithCd, $stereOff);

echo $remoteControl;

$remoteControl->onButtonPressed(0);
$remoteControl->offButtonPressed(0);
$remoteControl->onButtonPressed(1);
$remoteControl->offButtonPressed(1);
$remoteControl->onButtonPressed(2);
$remoteControl->offButtonPressed(2);
$remoteControl->onButtonPressed(3);
$remoteControl->offButtonPressed(3);

With this example we learned new but pretty useful null object trick. Sometimes, null object is being mentioned as a design pattern. In our example the null object instance was NoCommand class. We didn’t have a meaningfull object to assign to each slots out of the box, so we provided a NoCommand object that does nothing:

#
class NoCommand implements Command {
    public function execute() {}
}

By using this pattern we didn’t have to handle null values in RemoteControl::onButtonPressed() and RemoteControl::offButtonPressed() methods.

#
public function onButtonPressed($slotNo) {
    if( !is_null( $this->onCommands[$slotNo] ) ) {
        $this->onCommands[$stotNo]->execute();
    }
}

As a result we have a cleaner code.

This was pretty easy. The only thing left is the implementation of undo functionality. And with command pattern it comes quite easy as well: we add undo() method to our Command interface and implement it in all command classes. In example in LightOnCommand class the method looks like:

#
public function undo() {
    $this->light->off();
}

Next step is to change few things in our RemoteControl class. We add there undoCommand field, undoButtonPressed() method and add one line to both: onButtonPressed() and offButtonPressed():

# ...

public function onButtonPressed($slotNo) {
    $this->onCommands[$slotNo]->execute();
    $this->undoCommand = $this->onCommands[$slotNo];
}

public function offButtonPressed($slotNo) {
    $this->offCommands[$slotNo]->execute();
    $this->undoCommand = $this->offCommands[$slotNo];
}

public function undoButtonPressed() {
    $this->undoCommand->undo();
}

# ...

To test it we can play a little bit with our living room light and add these lines to our application code:

# 
$remoteControl->onButtonPressed(0);
$remoteControl->offButtonPressed(0);
$remoteControl->undoButtonPressed();
$remoteControl->offButtonPressed(0);
$remoteControl->undoButtonPressed();
$remoteControl->offButtonPressed(0);

And this is basically everything we were requested to implement to fulfill the requirements from the order. However, authors present us also a MacroCommand which is a specific example of using Command objects in a group and describe two more way of command pattern: queuing and logging requests.

Other examples

I didn’t find many different examples of usage of command pattern. There is one nice blog post with implementation of job queue in PHP. I like it because in the example a usage of SplQueue is presented. The showcase of JavaScript implementation of command pattern is another positive thing in the post. I also found out at least one person, Dhana Shunmugasundram, had similar idea to mine: write on a blog about design patterns described in Head First: Design patterns. It seems she stopped at command pattern. Let’s hope I’ll have more patience ;)

I mentioned at the beginning about PHPUnit. Reading about client, command, invoker and receiver, about invocation recalled in my mind names I had seen in PHPUnit package: PHP_Invoker, PHPUnit_Framework_MockObject_Invocation, PHPUnit_Framework_MockObject_Invokable and when I took a closer look into PHPUnit code it seems there are many decoupled functions. But after a while I think it’s hard to find there command pattern. I think, there are more encapsulated algorithms and more usages of strategy pattern. However, I’ve read somewhere on the Internet that command pattern is a simpler version of strategy pattern. There are also lots of usage of built-in PHP Reflection API. And I think ReflectionFunction::invoke() method is another nice example of command pattern usage: it encapsulate the invokation of reflected function/method.

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: https://blog.lukaszewski.it/2013/06/30/design-patterns-command/

May 25

Design patterns: singleton

This month I’d like to write about singleton pattern and tell you how it’s described in Head First: Design Patterns book. This chapter was one of the shortest in the book, so far. I read it a while ago and wanted to post about it earlier but as always… lack of free time didn’t let me do this ;)

Despite the fact we learn about what a singleton is at the beginning, there is still a case study which helps us learn more. This time it’s a chocolate factory! :) We’re presented with a controller class of chocolate boiler in Choc-O-Holic Inc. The class looks like this:

class ChocolateBoiler {
  private $empty;
  private $boiled;

  public function __construct() {
    $this->empty = true;
    $this->boiled = false;
  }

  public function fill() {
    if( $this->isEmpty() ) {
      $this->empty = false;
      $this->boiled = false;
      // fill the boiler with a milk/chocolate mixture
    }
  }

  public function drain() {
    if( !$this->isEmpty() && $this->isBoiled() ) {
      // drain the boiled milk and chocolate
      $this->empty = true;
    }
  }

  public function boil() {
    if( !$this->isEmpty() && !$this->isBoiled() ) {
      // bring the content to a boil
      $this->boiled = true;
    }
  }

  public function isEmpty() {
    return $this->empty;
  }

  public function isBoiled() {
    return $this->boiled;
  }
}

The authors of the code made everything to prevent of happening something bad. Just look at all of the if statements. It’s impossible to fill not an empty boiler, drain an empty boiler or not boiled content and boil an empty boiler or already boiled one. But things might get wrong if there are more ChocolateBoiler instances. That’s why we’re asked to change a little bit the class and use singleton pattern:

class ChocolateBoiler {
  private $empty;
  private $boiled;
  private static $instance = null;

  public static function getInstance() {
    if( is_null(self::$instance) ) {
       self::$instance = new self();
    }

    return self::$instance;
  }

  private function __construct() {
    $this->empty = true;
    $this->boiled = false;
  }

  public function fill() {
    if( $this->isEmpty() ) {
      $this->empty = false;
      $this->boiled = false;
      // fill the boiler with a milk/chocolate mixture
    }
  }

  public function drain() {
    if( !$this->isEmpty() && $this->isBoiled() ) {
      // drain the boiled milk and chocolate
      $this->empty = true;
    }
  }

  public function boil() {
    if( !$this->isEmpty() !$this->isBoiled() ) {
      // bring the content to a boil
      $this->boiled = true;
    }
  }

  public function isEmpty() {
    return $this->empty;
  }

  public function isBoiled() {
    return $this->boiled;
  }
}

Now, when anyone tries to create an instance of ChocolateBoiler she’ll have to use ChocolateBoiler::getInstance() method. Otherwise this line of code:

$chocolateBoiler = new ChocolateBoiler();

restults with:

PHP Fatal error:  Call to private ChocolateBoiler::__construct() from invalid context

After that we read the singleton pattern’s definition:

The Singleton Pattern ensures a class has only once instance, and provides a global point of access to it.

And basically the PHP part must end here. Rest of the chapter in the book describes some other issues developers should be aware of when implementing Singleton pattern in Java. The Java application might work in few threads. That means that different code lines might be executed separately. Authors describes few different ways of how to deal with multi-threading in Java.

Last time I’ve checked there were no core multi-threading concepts in PHP. However, you could find lots of solution which described how to simulate it. One of them was even lectured at our polish php event. I left links I’ve found on the Internet about PHP and multi-threading. But recently I’ve read about pthreads which is still an experiment.

Other examples

I didn’t search for it long, therefore I didn’t find any examples of how to implement Singleton in PHP with pthreads used. The only one common thing in the all PHP examples I’ve read is some more PHP magic ;) In the examples above I used __construct() magic function but __clone() and/or __wakeup magic method is commonly used as well:

class SingletonExample {
  public function __clone() {
    trigger_error('Cloning instances of this class is forbidden.', E_USER_ERROR);
  }

  public function __wakeup() {
    trigger_error('Unserializing instances of this class is forbidden.', E_USER_ERROR);
  }
}

Singleton examples

Multi-threading

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: https://blog.lukaszewski.it/2013/05/25/design-patterns-singleton/

Apr 30

Design patterns: factory

Next chapter in the book is quite long but it presents actually two design patterns: factory method and abstract factory. Both are explained to the reader in the same context: you are an owner of successful pizza shop. At the beginning the code of an application which helps you with your pizza shop is really simple:

class PizzaStore {
   public function orderPizza($type) {
      $pizza = null;

      if( $type === 'cheese' ) {
         $pizza = new CheesePizza();
      } else if( $type === 'greek' ) {
         $pizza = new GreekPizza();
      } else if( $type === 'pepperoni' ) {
         $pizza = new PepperoniPizza();
      }

      if( is_null($pizza) ) {
         return false;
      }

      $pizza->prepare();
      $pizza->bake();
      $pizza->cut();
      $pizza->box();

      return $pizza;
   }
}

But your clients expect from you to add more different kinds of pizza and this simple piece of code becomes bigger and bigger. Later you will probably have to remove some types of pizza because they will not sell well. The application code clearly is not closed for such modification. And when it got really big it will be easy to introduce bugs. As learnt earlier in the book we should encapsulate parts which changes. At this point in the book simple factory “pattern” is presented. It is not a real pattern but it is a warm-up before the factory method is described.

And this moment comes when you are informed that your pizza shop is doing so well that you have trounced the competition and are going to franchise your PizzaStore. And here comes first issue: there are different types of pizza depending on geographical region. Our pepperoni pizza in New York will have different crust and cheese than pepperoni pizza in Italy. First approach is to create different SimpleFactory subclasses which we pass as a parameter to PizzaStore constructor. So, the simple code would look like:

$nyPizzaFactory = new NYPizzaFactory();
$nyStore = new PizzaStore($nyPizzaFactory);
$nyStore->order('Veggie');

$chicagoPizzaFactory = new ChicagoPizzaFactory();
$chicagoStore = new PizzaStore($chicagoPizzaFactory);
$chicagoStore->order('Veggie');

But we’d like to have more control to make sure nothing but pizza type changes in whole pizza-making process. You decide to change PizzaStore to an abstract class with abstract method createPizza. PizzaStore::createPizza() returns Pizza object which in our case can be an instance of NewYorkPizzaStore or ChicagoPizzaStore subclasses. The whole logic which was above deciding what Pizza instance should be returned depending on $type is now in new factory methods: NewYorkPizzaStore::createPizza() or ChicagoPizzaStore::createPizza() in example:

class NewYorkPizzaStore extends PizzaStore {
   public function createPizza($type) {
      $pizza = null;

      if( $type === 'cheese' ) {
         $pizza = new CheesePizza();
      } else if( $type === 'greek' ) {
         $pizza = new GreekPizza();
      } else if( $type === 'pepperoni' ) {
         $pizza = new PepperoniPizza();
      }

      if( is_null($pizza) ) {
         return false;
      }

      return $pizza;
   }
}

At the end we are introduced to definition of:

The Factory Method define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantion to the subclasses.

In terms of factory method we usually mention creator classes and product classes. In the example from our book the creators are all subclasses of PizzaStore (ie. NewYorkPizzaStore) classes and products are different classes which extends from Pizza base class.

Factory method helps our with sticking to another design principle: Dependency Inversion Principle. Without our factory method our PizzaStore was closely connected to all *Pizza classes (ie. NewYorkStyleCheesePizza). PizzaStore was depended on other pizza types. If we had changed anything in PizzaStore we did have to change all classes it was depended on. With implementation of abstract Pizza class PizzaStore is now depended only on Pizza.

After contemplation about DIP we got back to our pizza store. It occurs (how surprisingly!) that in different regions not only pizza crust is different. The pizza ingredients differs as well! So, the cheese in New York is different than cheese in Chicago. Surely in near future we’ll have another group of regionally different ingredients. What happens next? We’re lead step by step with building PizzaIngredientFactory (the base interface and its regional subclasses), we implement changes in Pizza class and finally changes in PizzaStore. After those changes the flow looks like:

  1. Application creates an instance of PizzaStore:

            $newYorkPizzaStore = new NewYorkPizzaStore();
         
  2. It takes the order:

            $newYorkPizzaStore->orderPizza("cheese");
         
  3. The PizzaStore::orderPizza() method calls PizzaStore::createPizza():

            $pizza = $this->createPizza("cheese");
         
  4. Here the ingredient factory is being used:

            $pizza = new CheesePizza($this->newYorkIngredientsFactory);
         
  5. Next step is to prepare the pizza. Once it’s called, the factory method is asked to prepare ingredients:

            class CheesePizza extends Pizza {
            
               // ...
               
               public function prepare() {
                  $this->dough = $this->factory->createDough();
                  $this->sauce = $this->factory->createSauce();
                  $this->cheese = $this->factory->createCheese();
               }
            }
         
  6. Finally, we have the prepared pizza in hand and the PizzaStore::orderPizza() method bakes, cuts and boxes the pizza.

And at this point we’re introduced to:

The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

And it’s quite complicated diagram:

Abstract factory pattern diagram

Abstract factory pattern diagram from Head First: Design Patterns

At the end of this chapter we are presented with really nice comparison of these two new patterns: Factory Method and Abstract Factory. We’re explained that their are really similar but shouldn’t be lump in with each other. We should use Abstract Factory whenever we have families of products we need to create and we want to make sure our clients create products that belong together. And we should use Factory Method to decouple our client code from concrete classes we need to instantiate, or if we don’t know ahead of time all the concrete classes we are going to need.

Other examples

Since the factory patterns creates instances of objects there are lots of examples on the Internet. Most of the first results in Google I get are rather hypothetical problems. Mostly those are results of pages where authors try to teach readers about the patterns. But one of them is really close to reality. It’s about creating images with factory method pattern.

However, what comes to my mind there probably are many form builders which use factory patterns. In Wikia I recall nice example of code when we use factory to create social media widgets.

I didn’t put many code snnipets in this post but you can download code examples of both: factory method and abstract factory.

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: https://blog.lukaszewski.it/2013/04/30/design-patterns-factory/

Mar 31

Design patterns: decorator

It is about time for next design pattern which I have learnt by reading the book I have already mentioned several times[12] on this blog ;) Let’s do not make this prelude too long and start with book examples of decorator pattern.

Book examples

This time we learn Starbuzz Coffee. They got really popular and their ordering systems can not handle updates well enough anymore. They have just used inheritance and a simple model. The abstract base class Beverage has four subclasses: HouseBlend, DarkRoast, Decaf and Espresso. Each of the subclasses has to implement their own cost() method. At first look this model makes sense. But then in reality people would like some additional condiments added to their coffee, don’t they? Starbuzz Coffe must include it into their ordering system and doing that with the inheritance model looks like a nightmare.

Class explosion

Overused inheritance in Starbuzz Coffe.

Another idea was to move condiments to the base class, add setter and getter methods and implement cost() methods in the way they check if a beverage is being served with or without a condiment. Of course it is a bad idea again. It decreases number of classes in our codebase but every time if there is a change we need to implement it in the existing code. At this point in the book we learn how decorator pattern works.

The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

It might not tell enough. Maybe a look at pseudo-UML diagram will be helpful:

starbuzz decorator diagram

Starbuzz example of usage of decorator pattern

The abstract decorator class CondimentDecorator inherit from the base abstract class mostly to achieve type matching but not to get behavior. A decorator has to match type with an object it is going to decorate. We are explained also that we could have used here interface to match types but as the code had already base abstract class there was not need to alter existing code.

The few code snippets should help understand everything more deeply. Similar to previous posts, I have written PHP version of the code attached to the book.

class Espresso extends Beverage {
	public function __construct() {
		$this->description = "Espresso";
	}
  
	public function cost() {
		return 1.99;
	}
}
class Whip extends CondimentDecorator {
	protected $beverage;
 
	public function __construct(Beverage $beverage) {
		$this->beverage = $beverage;
	}
 
	public function getDescription() {
		return $this->beverage->getDescription() . ", Whip";
	}
 
	public function cost() {
		return .10 + $this->beverage->cost();
	}
}
$beverage = new Espresso();
$beverage = new Whip($beverage);
echo $beverage->getDescription() . " $" . $beverage->cost() . "\n";

Espresso is a regular beverage which we decorate with whip. The total cost is a result of calling cost() method on Whip decorator. The decorator delegates the task to decorated object and returns sum of its and Espresso costs.

Other examples

Except this nice coffee making scenario example (which can be found on Wikipedia as well) authors in the book mentions also Java I/O package where you can find lots of decorators. You can read about abstract component InputStream, abstract decorator FilterInputStream and different subclasses of InputStream and of FilterInputStream. You can decorate FileInputStream with BufferedInputStream and decorate it as well with LineNumberInputStream.

As it goes for PHP I did not find any built-in features. But there are lots of examples of using decorator pattern. You can use it to build HTML forms, to build useful classes which helps in flexible way operate on Strings or you can decorate existing validators of a form.

I remembered that when I used Symfony 1.4 I read about decorator pattern first time. It was used there to manage templating system. Symfony 2 strongly encourage to use Twig templating library and its inheritance in templates (which at the end is decorator pattern).

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: https://blog.lukaszewski.it/2013/03/31/design-patterns-decorator/

Feb 23

Design patterns: observer

As I promised myself every month one design pattern from the book will be described by me on this blog. This month’s design pattern is the observer pattern. I will start with definition this time:

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

Head First. Design Patterns.

Book examples

There are lots of examples in the book comparing to previous chapter. The observer pattern is compared to newspaper subscription where a newspaper publisher delivers you every edition of the newspaper. You can also unsubscribe and therefore you will not get the newspaper again (unless you start subscribing it again). After this real-life example there is a funny story described. It is called “A day in the life of the Observer pattern”. It also explains with some text and images the way Observer pattern works. But it is still not the end of examples. After the mentioned story we are presented with a comic telling a story of a head hunter and two developers.

All those examples have something in common: there is a subject (the newspaper publisher, the head hunter) and observers (newspaper readers, developers). The observers can get onto “subscribers list” of the subject and then the subjects can inform the observers about changes. The observers can also ask for deletion from the “subscribers list” and therefore they will not get information from subjects anymore. Diagram below presents the observer pattern and basing on it authors of the book lead the reader, step by step, to implementing his own observer pattern.

observer pattern diagram

Observer design pattern diagram from “Head First. Design Patterns” book

This own implementation is connected to the main example and issue described in the book: the weather monitoring application. The application should be build for our business partner and should display: current state of weather, forecast and statistic data. We get WheaterData class from our partner which has three interesting for us getters: getTemperature(), getHumidity() and getPressure(). There is also an empty method measurementsChanged() which is sign for us that we should focus on it and expand it. Of course the answer how to develop it is simple: use the observer pattern. We end up with the code you can download from here and run it in your terminal (I have re-written it from Java to PHP).

After that a new requirement appears and we are presented with more flexible in terms of passing measurements solution. The solution is build-in in Java SDK classes: java.utils.Observable and java.utils.Observer. However, authors explain us it is not flexible enough since we can not customize it. They present us also other build-in in Java examples of usage of the observer pattern such as listeners in Swing library. If it goes about PHP since version 5.1 we can use SplSubject and SplObserver interfaces.

Other examples

The listeners in Swing library reminded me at once event listeners in JavaScript. So, this is the example when we didn’t implement the observer pattern but we use it :) Also, most of today’s web applications use libraries such as jQuery and it has the trigger() method which we can use instead of implementing the observer pattern. Many examples on the Internet shows using the observer pattern to push AJAX requests via it (i.e. pushing tweets).

It seems the observer pattern in PHP is being used for different logging mechanisms. There are different user or authorization classes implementing Subject/Observable interfaces and once its statuses change all the loggers (which implement Observer interface) are being notified. An interesting example from one of first ten results in Google Search is upload manager which implements Subject interface and notifies a model which puts data into a database table and a logger which puts log data into a log file.

Other design patterns

Here is the list of described by me design patterns:

Permanent link to this article: https://blog.lukaszewski.it/2013/02/23/design-patterns-observer/

Jan 14

Design patterns: strategy

I became a little bit lazier at the end of previous year. Of course in terms of taking care of this blog ;) But, new year has come! And as it usually is new goals are slowly being visible on the horizon. One of those goals for me will be getting more familiar with software design patterns. I have been programming, creating lines of code for a quite long now and probably once or few more times I used a design pattern. But what I would like to achieve is to think and be able to talk to others in a specific way — design pattern’s way ;)

I thought about it earlier. I even bought myself really interesting book recommended to me by many others: Head First. Design Patterns. I read some of the chapters but not all. And the book has been lain untouched on my bookshelf for a little bit more than a year now. So, an idea has come to my head with the goal I would like to achieve this year: I will be describing here a design pattern from the book each month. This month I would present the strategy design pattern.

Book examples

There are “only” two examples in the book and both are written in Java (as all other examples in this book). The first one is funny and describes a duck simulator ;) At the beginning we are presented with standard object-oriented code with inheritance used:

class Duck {
  public function quack() {
    echo 'Quack! Quack!';
  }
  public function swim() {
    //swimming implementation
  }
  public function display() {
    echo 'Duck.';
  }
}

class MallardDuck extends Duck {
  public function display() {
    echo 'Mallard duck!';
  }
}

class RedheadDuck extends Duck {
  public function display() {
    echo 'Redhead duck.';
  }
}

Pretty simple — as the new requirement presented on next pages of the book: “we would like to add flying ducks to our application”. The first idea which came to the mind was to add fly() method to our base class Duck.

But it was not as good idea as it supposed to be: probably another developer added RubberDuck sub-class to the simulator and it started “to fly”. And it was not well-received during demo of the application. We could stop here and think about what if there are other types of ducks which do not fly or event do not quack? Keeping in mind that we need overwrite their fly() and/or quack() methods does not sound as the best way to use our time.

Another doubtful idea is to use interfaces:

interface IFlying {
  public function fly();
}

interface IQuacking {
  public function quack();
}

class Duck {
  public function swim() {
    //swimming implementation
  }
  public function display() {
    echo 'Duck.';
  }
}

class MallardDuck extends Duck implements IFlying, IQuacking {
  public function fly() {
    //flying implementation
  }
  public function quack() {
    echo 'Quack! Quack!';
  }
  public function display() {
    echo 'Mallard duck!';
  }
}

class RedheadDuck extends Duck implements IFlying, IQuacking {
  public function fly() {
    //flying implementation
  }
  public function quack() {
    echo 'Quack! Quack!';
  }
  public function display() {
    echo 'Redhead duck.';
  }
}

class RubberDuck extends Duck implements IQuacking {
  public function quack() {
    echo 'Squeak! Squeak!';
  }
  public function display() {
    echo 'Yellow, rubber duck.';
  }
}

class DecoyDuck extends Duck {
  public function display() {
    echo 'Wooden decoy duck.';
  }
}

What is wrong with this example (it seems quite logic, doesn’t it)? Well, the duplication of code is something we should always avoid (quack() methods in alive ducks’ classes). Also, the time spend on introducing new sub-class is even longer than overwriting two methods. After this funny example we are introduced with strategy design pattern. I used here some kind of UML-like diagram instead of putting more code. However, I re-written the code from Java to PHP and you can download and run in a terminal.

strategy pattern diagram

Strategy design pattern diagram from “Head First. Design Patterns.” book

The second example in the book is an exercise just to remember better the strategy pattern. The reader sees different parts of a diagram and is asked to put them in order. There are:

  • Character base class,
  • King, Qeen, Knight, Troll sub-classes,
  • WeaponBehavior interface,
  • KnifeBehavior, SwordBehavior, AxeBehavior, BowAndArrowBehavior classes.

She is also asked to put this method into right class:

public function setWeapon(WeaponBehavior $w) {
  this.weapon = $w;
}

I will not put the solution here just in-case if anyone would like to solve it ;) But this is the second example in the book of use of strategy pattern.

Other examples

The examples in the book do not have much in common with web development, do they? So, once I have made my mind to write this post I checked Internet if there are any good examples. Of course, there are plenty of them. But the top of searching results, I found, were about different ways of displaying a book title, finding a transportation way or encapsulating different database algorithms.

Definition

At the end, just as in the book, I will just put definition of strategy pattern:

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Head First. Design Patterns.

Also, you can use Wikipedia to find another definition but it does not vary much. Actually in English Wikipedia the definition is from the book I mentioned hundreds times in this post ;)

Permanent link to this article: https://blog.lukaszewski.it/2013/01/14/design-patterns-strategy/

Oct 28

Mouse middle-click and WebKit browsers

Recently, I worked on a bug reported by our user about broken middle-click functionality on one specific page. First what you do when you found such a bug report you are trying to reproduce it. I went to this page in production environment using Firefox and everything worked as expected. I went to this page served by my development machine and it worked. It seemed somebody, somehow fixed it (probably by accident because the bug report was not closed). But something told me to try it out also in Google Chrome. I started debugging it, later I showed it to my colleagues and one of them said: “I hate Google Chrome! It’s another IE but it’s IE of these days!”. I admit, he might have overreacted a little bit but it was not Google Chrome only issue. Later, we found out all browsers acts the same about middle-click except those ones based on WebKit engine.

WebKit browsers treat middle-click the same as left-click and fire click event. In example, they fire all functions bind to link via jQuery click() method.

Example

Imagine you want to track different events on a page to make sure everything works as you expected and to track how users use it in order to make the product even better for them. You are implementing tracking function similar to this one:

// File: tracking.js

//Event tracking function
function trackEvent(eventName, data) {
   if (data && data.href && typeof event != 'undefined') {
      event.preventDefault();
   }

   // Here goes logic responsible for choosing place where we store
   // tracking information and for storing those data

   //delay at the end to make sure all of the above was at least invoked
   if (data && data.href ) {
      setTimeout(function() {
         document.location = data.href;
      }, 100);
   }
}

The function accepts two arguments: eventName and data. First one could be our name of an event in example image-click, link-click, impression, scroll, hover. Second one is an object with different fields which are tracking data stored by us in our system. The function works in simple way: it gets the arguments, stores tracking data and mostly that’s all. This is its main task: to store given data. How does it gets the data? Simply, we use this function in our modules, new features on a page etc.

Imagine, you are releasing new menu on your page. You want to track all clicks in the new menu but you want to know which of those are clicks on sub-menu links and which are not. You also want to know how many users visits sub-pages of your page by using only the menu and not in example using search results or by typing a sub-page address directly in a browser’s address field. In order to do that, you are adding a small part of new code in your NewMenu.js file:

// File: NewMenu.js

NewMenu = {
   init: function() {
      //...
      $('#NewMenu a').click(function(e) {
         var target = $(e.target),
             href = target.attr('href');
 
         if( target.hasClass('submenu') ) {
            trackEvent('link-click', {
               feature: 'new-menu-submenu-element',
               href: href
            });
         } else {
            trackEvent('link-click', {
               feature: 'new-menu-main-element',
               href: href
            });
         }

         $.storage.set('entryPoint', 'newMenu');
      });
   },
   //...
}

And to your main.js file you put this simple mechanism which is tracking an entry point of a page:

// File: main.js

var entryPoint = $.storage.get('entryPoint');
if( entryPoint) {
   trackEvent('impression', {
      feature: 'new-menu-page-opened',
   });
   $.storage.set('entryPoint', null);
}

Except firing trackEvent() function with each anchor click in new menu the entryPoint variable is set in local storage of the browser. Then, after JavaScript is loaded on a subpage and entryPoint variable is found in local storage another trackEvent() call is fired to store data that a user used new menu to get to this page.

Let’s go back to the second parameter of the tracking function because this is the most important one here. Depending on the fact if data object has href field set or not our trackEvent() function will act differently. So, after a sub-page is loaded tracking function is called, it saves data to our tracking storage and that’s all. It doesn’t affect an end-user. But if the user clicks a link from #NewMenu container the data object passed to tracking function will have href field. And according to the code it will take 100 milliseconds and after that time load the page from data.href value. And this case affects the user, however, as long as he uses his mouse’s left button to click on a link the way he will be affected is only 100 milliseconds delay. If he uses his mouse’s middle button to click on a link and it all happens in Firefox or any other non-webkit browser it will only be a 100-milliseconds delay. But if he uses his mouse’s middle button to click on a link and WebKit browser he will get feeling his mouse’s middle button does not work on this page correctly.

Final thoughts

I am still not sure if in this case WebKit creators are “IE of these days” or not. On one hand it is annoying their engine does not handle middle-click as any other browsers do. But on another hand it is a click and a click event should be fired if you look at that from this point of view. At the end of the day, I have added one more parameter to data which is being passed to tracking function and we agreed to treat middle-click as a left click in our tracking statistics. Basically, it does the same but in a new browser tab. But I am also not sure about this solution once I read about which or button properties.

//File tracking.js

//Event tracking function
function trackEvent(eventName, data) {
   var data.button = data.button || false;
   
   if (data && data.href && typeof event != 'undefined') {
      event.preventDefault();
   }

   // Here goes logic responsible for choosing place where we store
   // tracking information and for storing those data

   //delay at the end to make sure all of the above was at least invoked
   if (data && data.href ) {
      setTimeout(function() {
         invokeDelayedClick(data.href, data.button);
      }, 100);
   }
}

function invokeDelayedClick(location, button) {
   if( button === 1 || button === 4 ) {
      window.open(location);
   } else {
      document.location = data.href;
   }
}

Permanent link to this article: https://blog.lukaszewski.it/2012/10/28/mouse-middle-click-and-webkit-browsers/

Sep 29

javascript.pl

Almost two weeks ago Damian Wielgosik announced on his ferrante.pl blog new project connected directly with JavaScript: javascript.pl. Shortly after Damian’s post another post (on chemikpil.pl blog) about the project appeared. And Andrzej Mazur reminded on his blog that javascript.pl domain had been bought by Damian a while ago. He seemed glad that finally something is going to happen on this address.

The project is really interesting and is supposed to help newbies in web-development world. The short tips should be, in my believe, short enough not to tire the reader but also rich enough to provide her with up-to-date knowledge and good practices in JavaScript world. And everyone can make this knowledge-base bigger since its sources are available via GitHub. However, as the author mentioned in his blog post, the “merge” button will be clicked by him only after very subjective judgment. And I have already learnt about it since my pull request has been hanging there for a while ;)

But I still believe it is a good idea. And I will keep watching it :) I think polish Internet also received it very positively. And I found similar project called JavaScript Garden by reading comments below Damian’s post. Maybe he could ask authors of the garden to import some of their tips. At the begining, I thought it wasn’t good idea to duplicate the content, waste space. But on the other hand probably many people from Poland who would like to learn something would search on it in polish language. And maybe this is the reason why javascript.pl should stay alive for a long time and be updated as often as possible.

Permanent link to this article: https://blog.lukaszewski.it/2012/09/29/javascript-pl/

Aug 31

Even faster web sites summary

I’ve written a summary of first book about performance written by Steve Souders few months ago. And also few weeks ago, maybe months I’ve finished the next part of Souders performance books. But this book wasn’t written only by the web performance guru ;) I read chapters written by: Douglas Crockford, Ben Galbraith, Dion Almaer, Nicholas C. Zakas, Dylan Schiemann, Tony Gentilcore, Stoyan Stefanov, Nicole Sullivan,  It’s about time to write something about it! I’ll just put here my notes, I put down on a piece of paper while reading.

with() statement in JavaScript

I had no idea there is such a statement in JavaScript! And actually that’s good I’ve never heard of it. If you don’t know something exists you won’t use it ;) And basically this is what to do with with() statement in JavaScript — don’t use it!

Use local variables

I think at Wikia we all agree to use more often var than not to use it :p Of course there are some edge-cases when you want to use a global scope variable but you have to be very careful then. In case of performance in the book we can read it’s a very good habit to use local variables instead of property or array look-ups. There is a very nice graph showing that the fastest way to access data is accessing it via local variable. The differences between data access time for literal, local variable, array item and object property are different in different browsers but in all browsers we can observe that accessing a local variable is faster than an array item or an object property. So, do this:

function process(dataObj) {
   var count = dataObj.count;
   if( count > 0 ) {
      for( var i=0; i < count; i++ ) {
         processData(dataObj.el[i];
      }
   }
}

instead of this:

function process(dataObj) {
   if( dataObj.count > 0 ) {
      for( var i=0; i < dataObj.count; i++ ) {
         processData(dataObj.el[i];
      }
   }
}

Decrementation instead of incrementations in loops

But later in the same chapter we can read that the good example above can be optimalized even more in terms of performance. How? Look at this:

function process(dataObj) {
   var count = dataObj.count;
   if( count > 0 ) {
      for( ; count > 0; count-- ) {
         processData(dataObj.el[i];
      }
   }
}

It reads that decrementing the iterator toward 0 can result in savings of up to 50%!

Gziping can be ignored

There is a warning in chapter 9 that not all of our users gets gziped content once we configured the server to provide gziped content. There are third-party softwares which change the HTTP headers! Mostly, they are firewalls, anti-virus applications or ad-blocks. So, be aware of it, monitor your systems to find out if there are such poor users with “bad” software which changes HTTP headers and try to help those users.

pngcrush!

Shortly after Performance Team at Wikia got created the first thing the team did was optimizing our images. We’ve saved more than unnecessary 8MB to be served to our users! During our daily development we any new assets are being changed by us with pngcrush application. And this small but pretty useful piece of software was mentioned in this book as well. Use pngcrush on your images to remove from them data which won’t be used by your end user.

Domains sharing

In the first book, I’ve written about previously, we are encourage to use more than one domain to make browsers possible to send requests in parallel. This time Steve Souders did more tests and proved that probably the optimal amount of domains used on our website is two.

Iframes are bad

That’s because they block the parent window’s onload event when used in typical way. And, as it’s proven in the book, it slows the performance of the page. Author also gives us also some tricks we can use to make it working faster. Unfortunately, there aren’t the same ways which works in all browsers. For Chrome&Safari setting the iframe src attribute value dynamically works, for all other browsers we need to set the src attribute after onload event.

CSS optimalization!

This was the part I’ve enjoyed the most! Since, most of this book as the previous one touched front-end optimization and some back-end ways to make the performance better (apaches configuration mostly). I don’t say it’s wrong because it’s probably the most important part since Steve Souders formed the golden rule of performance but it was only about JavaScript. The last chapter in this book touches CSS! :)

It describes different types of selectors and how efficient they are. Then it gets to advices of how to use CSS selectors in more efficient way: rightmost first, avoid universal rules, don’t qualify ID selectors (div#toc), don’t qualify class selectors, make rules as specific as possible, avoid descendant selectors, avoid tag-child selectors, question all usages of the child selectors, rely on inheritance.

Permanent link to this article: https://blog.lukaszewski.it/2012/08/31/even-faster-web-sites-summary/

Jul 30

JavaScript promise

There is still this book on my shelf I am trying to finish: Head First Design Patterns. I know I could get a great knowledge, I do not have now, just by reading this book. But from the other site, I know that by only reading it I will not be able to make any use of that knowledge. So, I am still hoping I will start a series of posts about design patterns and using them with PHP. We will see…

Right now, I am getting known and using patterns we use in Wikia. One of recent ones every developer is encourage to use is the promise pattern knows in jQuery world as deffered object. As you might know from my previous posts [1, 2] or from Steve Souders’ books the performance golden rule is that front-end part of a website takes the most time of page loading in an end user’s browser. And to reduce this time one of the rules is to reduce HTTP requests our website is sending to the server. MediaWiki has its Resource Loader and it is a great tool to get some CSS stylesheets, javascript files in one request. But still the way it is written “traditionally” makes it a little bit unreadable.

Imagine we have a link and once it has been clicked an overlay layer is being displayed along with a DIV element over it. This DIV element contains a text with information what it is about and a button:

a simple bootstrap modal

We do not want to put this DIV in DOM once a page is loaded. What if a user does not click it? It will be a waste of bandwidth. It is better to load it on demand. But then we need to load the template and at least some styling for it. It will be at least two requests. What if we need additional JavaScript file with some logic for our DIV element or the button in the DIV? One request for the JavaScirpt file more. The pseudo javascript with jQuery would look like:

$.getResources(['modal.css', 'boostrap-modal.js'], function() {
   $.get('modal.php', function(template) {
      // once when we have all resources
      // modal.php -- the template
      // modal.css -- styling of the template
      // boostrap-modal.js -- some extra logic
      // we can display it
      $(document).html(template);
   });
});

The code is still not-so-bad. But imagine there are more and more complications and we need to put there more nested callbacks. It is getting more unreadable and maintenance of such a code is getting hard to do. More nested callbacks means more serialized HTTP requests — we should minimize this as well as we minimize the HTTP requests.

If we made $.getResources() and $.get()[3] promise compatible it will be easier to write, extend and maintenance:

// make all calls in parallel
$.when(
  $.getResources(['alert.css', 'alert.js']),
  $.get('alert.php')
).
done(function(dataFromGetResources, dataFromjQueryGet) {
  // called when both requested are completed
  // ...
}).
fail(function() {
  // something went wrong
  // ...
});

Isn’t it beautiful? And it works perfect! :) It makes the HTTP requests in parallel and it is easy to maintenance and extend. Of course you can not use promise pattern if one request depends on the response from the other one but it is the only disadvantage I recall at this moment. So, if we want to have a nice summary it would look like this:

Advantages

  • saves you from nested callbacks nightmare
  • several callbacks can be bound to the single promise
  • promises can be “wrapped” in a single promise
  • improves front-end performance by allowing HTTP requests to be made in parallel

Disadvantages

  • can’t use promises if at least one callback depends on results from another one

That’s all what I wanted to write :) If you are more interested how promise pattern works I can give you also a link to this deffered-js github project. There is a really nice explanation and you can use files of deffered-js in you small projects where you do not use jQuery in example.

References:

  1. Was Steve Souders wrong?
  2. Summary of “High Performance Web Sites” by Steve Souders
  3. jQuery.get() has already implemented promise interface

Permanent link to this article: https://blog.lukaszewski.it/2012/07/30/javascript-promise/

Older posts «

» Newer posts