Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

readme.md

Factory pattern

Factory pattern create instance for others.

Factory design pattern works like a factory in the real world in that it creates something for others to use. In the context of OOP, it helps in creating and instantiating objects.

Factory type

  • simple factory
  • abtract factory
  • factory method

simple factory

factory method

class DBFactory
{
  private $driver;

  public function setDriver($driver)
  {
    $this->driver = $driver
  }

  public function makeDB($host, $dbname, $user, $pass)
  {
     $db;
    if ($this->driver == 'mysql') {
      $db = new Mysql();
    }elseif ($this->driver == 'postgre') {
      $db = new Postgre();
    }else{
      $db = new Sqlite();
    }

    $db->setHost($host);
    $db->setDB($dbname);
    $db->setUserName($user);
    $db->setPassword($pass);
    $db->connect();

    return $db;
  }
}

$dbFactory = new DBFactory;
$dbFactory->setDriver('mysql'));
$DB = $dbFactory->makeDB("host", "db", "user", "pwd");

Abstract factory

abstract class Employee
{
  abstract public function info();

  public function getName()
  {
    return 'name: ' .  $this->info()->name();
  }
}

class HrInfo
{
  public function name()
  {
    return 'kamal';
  }
}

class Hr extends Employee
{
  public function info()
  {
    return new HrInfo();
  }
}

$hr = new Hr();
print_r($hr->getName());
// kamal

resources