Last active
January 12, 2020 11:27
-
-
Save sankety/74419853d429161c1138d94cb8f9c323 to your computer and use it in GitHub Desktop.
Demo for Factory Design Pattern in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class FactoryMain | |
{ | |
private $type; | |
function __construct($type) | |
{ | |
$this->type = $type; | |
} | |
public function getInstance() : TypeInterface | |
{ | |
if ( !class_exists($this->type)) { | |
throw new Error('Class implementation missing'); | |
} | |
return new $this->type(); | |
} | |
} | |
interface TypeInterface{ | |
public function someMethod(); | |
} | |
class TypeA implements TypeInterface | |
{ | |
function someMethod() | |
{ | |
return 'from TypeA'; | |
} | |
} | |
class TypeB implements TypeInterface | |
{ | |
function someMethod() | |
{ | |
return 'from TypeB'; | |
} | |
} | |
try { | |
$obj = new FactoryMain('TypeB'); | |
$ins = $obj->getInstance(); | |
echo $ins->someMethod(); | |
} catch (\Throwable $t) { | |
echo $t->getMessage(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment