Skip to content

Instantly share code, notes, and snippets.

@sankety
Last active January 12, 2020 11:27
Show Gist options
  • Save sankety/74419853d429161c1138d94cb8f9c323 to your computer and use it in GitHub Desktop.
Save sankety/74419853d429161c1138d94cb8f9c323 to your computer and use it in GitHub Desktop.
Demo for Factory Design Pattern in PHP
<?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