By Michael Williams, Published on 03/20/2016
In object-oriented programming (OOP), a factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class[1] from some method call, which is assumed to be "new". Wikipedia
<?php
class Automobile
{
private $make;
private $model;
private $price;
public function __construct(
$make,
$model,
$price
)
{
$this->make = $make;
$this->model = $model;
$this->price = $price;
}
public function getMakeModelAndPrice()
{
return [
'make' => $this->make,
'model' => $this->model,
'price' => $this->price
];
}
}
class AutomobileFactory
{
public static function create(
$make,
$model,
$price
)
{
return new Automobile(
$make,
$model,
$price
);
}
}
$automobile = AutomobileFactory::create('Honda', 'Pilot SUV', '$30,145');
var_dump($automobile->getMakeModelAndPrice());
// will output array(3) { ["make"]=> string(5) "Honda" ["model"]=> string(9) "Pilot SUV" ["price"]=> string(7) "$30,145" }
The above code is an example on how we can use a factory to create an object. With a factory, rather than calling new directly. The object is created in our factory class. If our Automobile class is modified in the future, with this approach we will only have to modify the code within our factory.