Created
April 26, 2013 13:50
-
-
Save ozgg/5467513 to your computer and use it in GitHub Desktop.
Factory and DI example
This file contains 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 Car | |
{ | |
protected $power; | |
protected $doors; | |
public static function factory($type, Engine $engine, Transmission $transmission) | |
{ | |
$instance = null; | |
switch ($type) { | |
case 2: | |
$instance = new Sedan($engine, $transmission); | |
break; | |
case 4: | |
$instance = new Crossover($engine, $transmission); | |
break; | |
default: | |
throw new Exception('Invalid type'); | |
} | |
return $instance; | |
} | |
public function __construct(Engine $engine, Transmission $transmission) | |
{ | |
$this->engine = $engine; | |
$this->transmission = $transmission; | |
} | |
} | |
class Sedan extends Car | |
{ | |
// implementation | |
} | |
class Crossover extends Car | |
{ | |
// implementation | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment