Skip to content

Instantly share code, notes, and snippets.

@ozgg
Created April 26, 2013 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozgg/5467513 to your computer and use it in GitHub Desktop.
Save ozgg/5467513 to your computer and use it in GitHub Desktop.
Factory and DI example
<?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