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.
- simple factory
- abtract 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 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