PHP OOP Design Patterns: Creational [5 How To Examples]

Previous Title: PHP OOP Design Patterns [18 How To Examples]

PHP OOP Creational Design Patterns


PHP OOP Singleton

The Singleton pattern returns a resource when called but only creates it on the first call.

<?php
// PHP Singleton OOP Design Pattern
class DatabaseSingleton
{
  private static $connection = null;
  private function __construct()
  {
  }
  public static function get_instance()
  {
    if (self::$connection == null) {
      try {
        // in a live scenario, credintials would be stored elsewhere
        $host = "";
        $db = "";
        $user = "";
        $pass = "";
        $connection = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
      } catch (PDOException $pe) {
        throw new Exception("Error :" . $pe->getMessage());
      }
    }
    return self::$connection;
  }
}
$conn = DatabaseSingleton::get_instance();

PHP OOP Factory Method

The Factory Method separates the creation and building of an object. This is useful if the end consumer wanting to build an object doesn’t need to know all the details of building it.

<?php
// PHP OOP Factory Method Design Pattern

class Soup
{
  private $name;
  private $beans;
  private $meat;

  public function __construct($name, $beans, $meat)
  {
    $this->name = $name;
    $this->beans = $beans;
    $this->meat = $meat;
  }

  public function getIngredients()
  {
    return $this->name . " has " . $this->beans . " and " . $this->meat;
  }
}

class SoupFactory
{
  public static function create($name)
  {
    if ($name == "chili") {
      return new Soup($name, "pinto beans", "hamburger");
    } else {
      return new Soup($name, "no beans", "chicken");
    }
  }
}

$chili = SoupFactory::create("chili");

echo $chili->getIngredients();

PHP OOP Builder Design Pattern

The Builder Pattern simplifies the creation of a complex, fully realized object.

It uses the following pieces:

  • Concrete Class to set the root base of an empty object to be built.
  • Interface to set the skeleton of what the object should conform to.
  • Builder Implementation to set the specifics of how object types should be built.
  • Director Class to call the final build of the object and return it.
<?php
// PHP OOP Builder Design Pattern

// Concrete Class
class HomeConcrete
{
  public $bedrooms;
  public $type;
  const APARTMENT = "Apartment";
  const SINGLE_FAMILY = "Single Family";
  public function __construct()
  {
  }
}

// Builder Interface
interface HomeBuilderInterface
{
  public function setType();
  public function setBedroomsCount();
  public function getHome();
}

// Builder Implementation
class ApartmentBuilder implements HomeBuilderInterface
{
  private $home;
  public function __construct(HomeConcrete $home)
  {
    $this->home = $home;
  }
  public function setType()
  {
    $this->home->type = HomeConcrete::APARTMENT;
  }
  public function setBedroomsCount()
  {
    $this->home->bedroom = 2;
  }
  public function getHome()
  {
    return $this->home;
  }
}

// Builder Implementation
class SingleFamilyBuilder implements HomeBuilderInterface
{
  private $home;
  public function __construct(HomeConcrete $home)
  {
    $this->home = $home;
  }
  public function setType()
  {
    $this->home->type = HomeConcrete::SINGLE_FAMILY;
  }
  public function setBedroomsCount()
  {
    $this->home->bedroom = 4;
  }
  public function getHome()
  {
    return $this->home;
  }
}

// Builder Director
class HomeDirector
{
  public function build(HomeBuilderInterface $builder)
  {
    $builder->settype();
    $builder->setBedroomsCount();
    return $builder->getHome();
  }
}

// Use the builder
$apartment_home = (new HomeDirector())->build(
  new ApartmentBuilder(new HomeConcrete())
);
$single_family_home = (new HomeDirector())->build(
  new SingleFamilyBuilder(new HomeConcrete())
);

print_r($apartment_home);
print_r($single_family_home);

PHP OOP Abstract Factory Design Pattern

The Builder Pattern simplifies the creation of a complex, fully realized object.

// this
  • Code on Github: PHP OOP Abstract Factory
  • Other Abstract Factory resources:

PHP OOP Prototype Design Pattern

The Builder Pattern is…

// this
  • Code on Github: PHP OOP Prototype Design Pattern
  • Other Prototype Pattern resources:

PHP OOP Design Patterns Reference

Leave a Comment