Let's take the manufacturer/car model example. A model has a specific manufacturer. So let's say the models "Punto", "500", "Panda" have always the manufacturer "Fiat".
If the models are one class each and the manufacturer is a class instance what's the cleanest/best solution to get the models connected to a manufacturer without having multiple instances of the manufacturer class. Setting them via constructor is obvious because a model can never change from who it gets manufactured.
Let's show my problem in a simplified code sample:
class Manufacturer
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
}
abstract class Car
{
protected $manufacturer;
public function __construct(Manufacturer $manufacturer)
{
$this->manufacturer = $manufacturer;
}
abstract public function getModel();
public function getManufacturer()
{
return $this->manufacturer;
}
}
class ModelA extends Car
{
public function getModel()
{
return 'A';
}
}
class ModelB extends Car
{
public function getModel()
{
return 'B';
}
}
// The manufacturer instance
$manufacturerC = new Manufacturer('C');
// Setting the manufacturer for the models is obvious
// because they always get manufactured from the manufacturer "C"
// and never from a manufacturer "X"
$modelA = new ModelA($manufacturerC);
$modelB = new ModelB($manufacturerC);
Aucun commentaire:
Enregistrer un commentaire