public
Created

Factory and DI example

  • Download Gist
factory_di
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
<?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
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.