Skip to content

Instantly share code, notes, and snippets.

@mangelsnc
Created December 4, 2017 00:18
Factory Pattern - After apply pattern Raw
<?php
class CarFactory
{
public function create($code)
{
switch ($code)
{
case 'HC':
return new HondaCivic();
case 'FF':
return new FordFocus();
case 'TA':
return new ToyotaAuris();
}
throw new InvalidCarException($code);
}
}
<?php
interface CarInfoInterface
{
public function getVendor(): string;
public function getModel(): string;
public function getEngine(): string;
public function getCv(): int;
}
<?php
class CarInformation
{
private $carFactory;
public function __construct(CarFactory $carFactory)
{
$this->carFactory = $carFactory;
}
public function getTitle($code)
{
$car = $this->carFactory->create($code);
return sprintf(
'<b>Model: <\b>\t %s %s\n<b>Engine: <\b>\t %s %sCV',
$car->getVendor(), $car->getModel(), $car->getEngine(), $car->GetCv()
);
}
}
<?php
class FordFocus implements CarInfoInterface
{
public function getVendor(): string
{
return 'Ford';
}
public function getModel(): string
{
return 'Focus';
}
public function getEngine(): string
{
return '1.0 Ecoboost';
}
public function getCv(): int
{
return 125;
}
}
<?php
class HondaCivic implements CarInfoInterface
{
public function getVendor(): string
{
return 'Honda';
}
public function getModel(): string
{
return 'Civic';
}
public function getEngine(): string
{
return '1.5 VTEC Turbo';
}
public function getCv(): int
{
return 182;
}
}
<?php
class ToyotaAuris implements CarInfoInterface
{
public function getVendor(): string
{
return 'Toyota';
}
public function getModel(): string
{
return 'Auris';
}
public function getEngine(): string
{
return 'Auris 120 T';
}
public function getCv(): int
{
return 116;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment