The factory design pattern in php explained

We consider the use of the factory pattern in those cases when we want the main part of our code(a.k.a. Business logic) to lớn address only the management of objects rather than their making.For these cases, the factory pattern instructs us khổng lồ separate the making of objects into a factory classwhile leaving the main part of the ứng dụng to handle the management of the objects.

Bạn đang xem: The factory design pattern in php explained

Let"s demonstrate some scenarios in which the factory thiết kế pattern can be beneficial:

If a class manages a shopping cart, it should deal only with shopping cart management (e.g., adding or removing products from the cart) & not be concerned with the manufacturing of those products.A warehouse management class follows the quantities of items entering & leaving the warehouse but has no interest in making those items.A car buying agency should simply track orders & not have to also giảm giá with the details of how the cars are made.
*

We consider the use of the factory pattern in those cases when we want the main part of our code khổng lồ address only the management of objects rather than their making.


What are the characteristics of the factory thiết kế pattern?

The factory thiết kế pattern has two main sections:

The main part of the ứng dụng that manages objects but does not make them.The factory class that makes the objects.

When khổng lồ consider the use of the factory kiến thiết pattern?

The factory pattern is a good solution for those cases in which the main part of the tiện ích needs to lớn manage the objects and not create them.

Let"s demonstrate this with a CarOrder class that handles cars orders.Each time a new oto is ordered, we call the order method và pass the oto type as a parameter ("r" or "s" model).The order method then makes a new oto object (based on the parameter) and adds the newly created oto object to the$carOrders array that stores the các mục of cars that were ordered.

class CarOrder protected $carOrders = array();protected $car;// Order & make the oto in the same method???!public function order($model=null)if(strtolower($model) == "r")$this->car = new CarModelR();else$this->car = new CarModelS();$this->carOrders<> = $this->car->getModel();public function getCarOrders()return $this->carOrders;In this textbook example, it does not seem lượt thích a bad idea to mix between the code that makes objects and the code that manages them. However, most of the code in real life is much more complex. For example, different oto models may very well need different chassis; the higher-end model may have extra comfortable seats or be a convertible, etc. It"s too much responsibility for a method whose sole purpose is khổng lồ order cars lớn handle their manufacturing as well.


The factory method

Once we establish that it is better not to lớn place the responsibility for the production of cars on the order method, we can try to lớn solve the problem by moving the code responsible for the production of cars to lớn a separate make method whose sole purpose would be khổng lồ produce cars.

Let"s look at the code after we"ve separated the class into the following two methods:

The order method manages the order of cars.The make method makes the car objects.

class CarOrder protected $carOrders = array();protected $car;// Order the car.public function order($model=null)$car = $this->make($model);$this->carOrders<> = $car->getModel();// The actual making of the oto is now separated into a method of its own.protected function make($model=null)if(strtolower($model) == "r")return $this->car = new CarModelR();return $this->car = new CarModelS();public function getCarOrders()return $this->carOrders;The code above demonstrates the making of objects in a dedicated make method.This approach is also known as the factory method. Using the factory method is legitimate và can certainly help in some casesbut not in all of them, due to lớn the following reasons:

The more methods we địa chỉ cửa hàng to the cars" manufacturing và order processes, the more we bloat the class and make it less readable and maintainable.We still make cars within the CarOrder class, which should engage only in orders & not in automobile manufacturing.

Xem thêm: Download Obey Me! Shall We Date? Obey Me! For Android

In order to lớn solve these problems, we use the factory pattern that instructs us khổng lồ move the making of objects khổng lồ a separate factory class.


The Factory class

Let"s create a dedicated CarFactory class with the make method that creates the car objects on demand:

class CarFactory protected $car;// Determine which model to manufacture, & instantiate // the concrete classes that make each model.public function make($model=null)if(strtolower($model) == "r")return $this->car = new CarModelR();return $this->car = new CarModelS();Now that we have a dedicated CarFactory class, we need lớn create an object out of it inthe constructor of the CarOrder classso we can use it"s make() method.

class CarOrder protected $carOrders = array();protected $car;// First, create the carFactory object in the constructor.public function __construct()$this->car = new CarFactory();public function order($model=null)// Use the make() method from the carFactory.$car = $this->car->make($model);$this->carOrders<>=$car->getModel();public function getCarOrders()return $this->carOrders;The main part of the ứng dụng needs lớn pass parameters lớn the factory class(in our example, it is a short string that tells the class which car object to lớn create)and, in return, it gets the objects. The advantage is obvious: the main part is now free to bởi its job without having to delve deeplyinto the technical details of how the objects (e.g., the dependencies that such an object may have) are made.

Understanding the example can lead us to lớn formulate the most important characteristic of the factory pattern:


When we use the factory pattern, we separate the making of objects into a dedicated class whose main responsibility is the making of objects.


The car classes

But what about the actual classes that make the car objects?For this purpose, we use a car interface, & implement it with concrete classes that make the r & s models.Let"s start with the interface which tells us what features all the oto objects need to have:

interface car function getModel();function getWheel();function hasSunRoof();Once we have an interface, we can write the concrete classesCarModelR & CarModelS that implement the interface.

The CarModelS:

class CarModelS implements car protected $model = "s";protected $wheel = "sports";protected $sunRoof = true;public function getModel()return $this->model;public function getWheel()return $this->wheel;public function hasSunRoof()return $this->sunRoof;The CarModelR:

class CarModelR implements car protected $model = "r";protected $wheel = "regular";protected $sunRoof = false;public function getModel()return $this->model;public function getWheel()return $this->wheel;public function hasSunRoof()return $this->sunRoof;The following UML diagram may help us in understanding the code structure and the connection between the classes:

*


Let"s demo the code

Let"s use the following code in order to test everything that we have written:

$carOrder = new CarOrder;var_dump($carOrder->getCarOrders());$carOrder->order("r");var_dump($carOrder->getCarOrders());$carOrder->order("s");var_dump($carOrder->getCarOrders());And the result:

array (size=0) empty array (size=1) 0 => string "r" (length=1) array (size=2) 0 => string "r" (length=1) 1 => string "s" (length=1)


In conclusion

We should consider the use of the factory thiết kế patternin those cases where we need to không tính phí a class from making the objects that it manages.For this aim, we make the objects in a dedicated factory class.


*

Joseph Benharosh is a full stack website developer and the tác giả of the eBook The essentials of object oriented PHP.


Was this tutorial helpful?

If so, the eBook"The essentials of object oriented PHP" can further help you.


*

"The essentials..." is an in-depth guide lớn help you quickly and easily increase your productivity & become a hot commodity in the job market.

Don"t waste time! Click on the green button khổng lồ buy the eBook & start achieving your potential today!