Skip to content

Instantly share code, notes, and snippets.

/Car.php Secret

Created February 8, 2015 22:32
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 anonymous/ca1a7a6552c6125b7032 to your computer and use it in GitHub Desktop.
Save anonymous/ca1a7a6552c6125b7032 to your computer and use it in GitHub Desktop.
Factory Method
<?php namespace Pattern\FactoryMethod;
interface Car {
}
<?php namespace Pattern\FactoryMethod;
use InvalidArgumentException;
abstract class CarFactory {
private $cars = [];
function __construct(array $cars)
{
$this->cars = $cars;
}
public function make($name)
{
if (! isset($this->cars[$name]))
{
throw new InvalidArgumentException('You tried to make a nonexistent car');
}
return new $this->cars[$name];
}
}
<?php namespace Pattern\FactoryMethod;
class CarStore {
private $factory;
function __construct(CarFactory $factory)
{
$this->factory = $factory;
}
public function order($name)
{
$this->factory->make($name);
}
}
<?php namespace Pattern\FactoryMethod\Factory;
use Pattern\FactoryMethod\CarFactory;
/**
* @codeCoverageIgnore
*/
class Chevrolet extends CarFactory {
private $cars = [
'equinox' => 'Pattern\SimpleFactory\Car\Equinox',
'miray' => 'Pattern\SimpleFactory\Car\Miray',
];
function __construct()
{
parent::__construct($this->cars);
}
}
<?php namespace Pattern\FactoryMethod\Car;
use Pattern\FactoryMethod\Car;
class Equinox implements Car {
}
<?php namespace Pattern\FactoryMethod\Car;
use Pattern\FactoryMethod\Car;
class Evos implements Car {
}
<?php namespace Pattern\FactoryMethod\Factory;
use Pattern\FactoryMethod\CarFactory;
/**
* @codeCoverageIgnore
*/
class Ford extends CarFactory {
private $cars = [
'evos' => 'Pattern\SimpleFactory\Car\Evos',
'galaxy' => 'Pattern\SimpleFactory\Car\Galaxy',
];
function __construct()
{
parent::__construct($this->cars);
}
}
<?php namespace Pattern\FactoryMethod\Car;
use Pattern\FactoryMethod\Car;
class Galaxy implements Car {
}
<?php namespace Pattern\FactoryMethod\Car;
use Pattern\FactoryMethod\Car;
class Miray implements Car {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment