The simplest Observer design pattern example

A few days ago I got involved in a chat about the usage of Object-oriented design patterns. I brought up the problematic of their usage when not needed, that ends up in adapting the code to the pattern and altering it, risking to increase its complexity. I mentioned an example of usage of the Observer design pattern, that I’ve seen used even where one object A (Subject) just needed to keep an array of reference of objects B (Observers), but B didn’t actually need to refer back to A.

From Wikipedia: The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

In this post, I’ll expose a case where the usage of that pattern is very simple to understand: a Newsletter system, with senders (Subject) and subscribers (Observers).

In this example, we have two users, John and Mike who both subscribe to the NewsletterSender (Subject). When the email is sent, both are notified by NewsletterSender::notifySubscribers() that iterates the users and call their update() passing its reference. Via this reference, the users will then be able to call the getter to read the email. So, John and Mike will both receive the reference to the NewsletterSender, John will print out the email text, but Mike only decides to say that there is an email (different implementation).

See the comment near each method with the classes and method names of the corresponding PHP interfaces SplObserver and SplSubject

97 things every programmer should know: personal notes

Last month I saw a book flying about the office, containing useful tips from developers. 97 suggestions from experienced developers. Amazon is still selling it, so I suggest you read it if work as a software developer or you occasionally dip into coding: 97 Things Every Programmer Should Know: Collective Wisdom from the Experts

I’ve finished reading it, and I took some notes while reading. Some concepts and suggestions were obvious, as I hear them many times from the community (blogs, conferences, colleagues) or I’ve already personally experienced them. I’ll paste those my notes here, with the hope that you can find something valuable from looking through them.

Continue reading

Class flags with bitwise operators

bitwise operatorsThere is a group of  PHP features that most of developers don’t usually use: bitwise operators.

These operators are widely used in the C language to make low-level applications (device drivers, protocols etc..). They are very useful when used in OOP developing as a flags for options in functions, classes and general settings.

Brief overview

There are 6 bitwise operators in PHP: And (&), Or (|), Xor (^), not (~), shift left(<<) and right(>>). I won’t to explain here their semantic as it’s not the purpose of this post, read the official documentation [link] if you don’t know how the bitwise operator work.

Use of as a flags : error_reporting

When an array of N binary (on/off) options is needed, the idea is using bitwise operators to store all the options within one integer value, that is a string (or array or word) of bits.
Normally, N constants are set to the values 1,2,4,8, … ,2^(N-1) so that with bitwise operator it’s possible to combine them and obtain any possible configuration of the string.
Continue reading

Singleton is bad !!

An interesting suggestion emerged from some speakers (1 and 2) of the last PHP UK conf is: do not use the Singleton design pattern !!

At the beginning it made me a little astonished as it’s one of the most widely used design patterns, in addition ZF and lots of other projects use it. However, after a while I agreed the idea. Singleton actually had created some problems when I had to do some class testing and refactoring in some PHP code.

Why is it not a good practice ? Singleton is appropriate when dealing with threads (JAVA, C#), but as a matter of fact in PHP applications it’s used just as a global constant and it creates dependency injection. That’s a bad practice as it couples the components/classes and usually makes difficult unit testing, refactoring and structural changes.
Continue reading

Design Pattern: Decorator

Decorator is similar to Proxy.

Basically, decorator is an extension (or wrapper) of the original class (component) and adds features.
A decorator contains a pointer to the component class (initialized by the constructor), and the methods of the component overridden.

class ImgComponent {
private $src;
private $alt;
public function __construct($name, $src) { /* assign to properties*/ };
public function getHTML() {
return "[ img src="{$this->src}" alt="{$this->alt}" /]";

Let’s write a decorator:

class ImgWithCaption extends imgComponent
private $caption;
private $imgComponent;
public function __construct(&$img, $caption) {
$caption->imgComponent = $caption;
$this->imgComponent = &$img;

public function getHTML() {
return "<div><div>{parent::getHTML()}</div>
<div> $caption</div></div>";

Design Pattern: Adapter

The Adapter design pattern is basically a wrapper, that is a class which provides methods to access to another class.

It’s commonly used to normalize incompatibile interfaces.
It’s similar to Proxy pattern, but it’s a little different. Proxy includes an object and controls accesses to it; Adapter provides an interface to the object, usually by inheritance.

class A {
public static function sort(array $ar) { ... }

class B {
private $ar;
public function __construct() {}
public function sortElements() { ... };
public function returnArray() { return $ar;}

Now we can extend B and provide the same interface as A

class BAdapter extends B {
public static function sort(array $ar) {
$b = new B($ar);
return $b->returnArray();

now we can use A and B2 in the same way:

print_r( A::sort(array(3,2,4)) );
print_r( BAdapter ::sort(array(3,2,4)) );

Design Pattern: Proxy

It provides a filtered controlled access to an object, without exposing it directly.

How to implement in PHP5:
Declare a class:
  • constructor: instantiates the object (only the first time) and keeps the instance into a private properties
  • – implement the methods that provide a controlled access to the internal object
    – use the magic method __call($name, $value), then checks/filters the name and arguments, and may call call_user_func_array($func, $params). The $func parameter ($func) must be an array that contains the object (private property) and the function name ($name passed to __call).
For security obvious reasons, implement also the other magic methods, such as __clone(), __se()t, __get(), __toString()

Design Pattern: Factory

Factory is a creational design pattern which handles object creation.

A factory class provides the methods to create object (whit a superclass in common), but let subclasses to decide which class will be instantiated.
Basically, it contains a static method (“connect” in the example below) that accept one parameter and makes a switch on it. Depending on the parameter, a new object of different type is returned. Typical use is when we have a super class A and subclasses A1, A2, An, and we add a static method getAx($name) { … switching on $name and return a instance o A1 or A2… or An } .
Advantages: if we create a new type/subclass, we will not rewrite the code that create objects.
Following, a class (factory) “DB” with a static method that returns an instance (object MySQL or postgreeSQL, that implements the same interface), in according to the argument (connection string).

class DB
public static connect($connString)
ereg("([a-z]*)://([a-z]*):([a-z]*)@([a-z]*)/([a-z]*)",$connString, $reg);
list($tmp, $driver, $user, $pass, $host, $db) = $reg;
case "mysql": return new MySQL($host, $user, $pass, $db); break;
case "postgre": return new postgreSQL($user, $pass, $db, $host); break;
default: new Exception("connection string not valid !");
Example of use:
Now, let’s use the factory, regardless the class type

$conn1 = DB:: connect("mysql://user:pass@localhost/db");
$conn2 = DB:: connect("postgre://user:pass@localhost/db");

//$conn1 and $conn will only use method of the common superclass/interface, ex: query()

Design Pattern: Value

Consider a class Val which contains a value, and a method add() which add another value with the same type.

class Val {
public function
__construct($value=0) {$this->value = $value; }

public function get() { return $this->value; }

public function add($newVal) {
//(1) WRONG:
//$this->addV += $value; //WRONG !!

// (2) RIGHT !!
return new Val($this->value + $newVal->get());

Add directly the value to the internal properties (1) is wrong!!
Suppose to have a class ValContainer, with a properties that is a reference to object Val.

Two or more instances of ValContainer should be contains references to the same instance of Val (e.g. via another class which contains a Val instance and returns it).

If one instance calls the method add() of Val, the other instances will have the new value modified !! This is not in according to OOP principles !

The second method (2) is right, it instantiates another Val object in case of add() !!

Design Pattern Singleton

Singleton is a creational pattern which ensures a class has only one instance, and provide a global pointer to access it.

The most common example is a database connection.
The idea: the class doesn’t provide a constructor, but a method to return an instance. That instance is assigned to a static properties and is instantiated only at the 1st access.

class Example
// Hold an instance of the class
private static $instance;

// A private constructor; prevents direct creation of object
private function __construct() { }

// The singleton method
public static function singleton()
if (!isset(
self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;

// Prevent users to clone the instance
public function __clone() { trigger_error(‘Clone is not allowed.’, E_USER_ERROR); }