Skip to content

Instantly share code, notes, and snippets.

@Xelom
Created February 22, 2017 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xelom/8ab3ed060243a64611439f98de32c618 to your computer and use it in GitHub Desktop.
Save Xelom/8ab3ed060243a64611439f98de32c618 to your computer and use it in GitHub Desktop.
Simple Factory

Programmatic Example

First of all we have a door interface and the implementation

interface Door {
    public function getWidth() : float;
    public function getHeight() : float;
}

class WoodenDoor implements Door {
    protected $width;
    protected $height;

    public function __construct(float $width, float $height) {
        $this->width = $width;
        $this->height = $height;
    }
    
    public function getWidth() : float {
        return $this->width;
    }
    
    public function getHeight() : float {
        return $this->height;
    }
}

Then we have our door factory that makes the door and returns it

class DoorFactory {
   public static function makeDoor($width, $height) : Door {
       return new WoodenDoor($width, $height);
   }
}

And then it can be used as

$door = DoorFactory::makeDoor(100, 200);
echo 'Width: ' . $door->getWidth();
echo 'Height: ' . $door->getHeight();

When to Use?

When creating an object is not just a few assignments and involves some logic, it makes sense to put it in a dedicated factory instead of repeating the same code everywhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment