What is the Factory Method Pattern? Let's implement it in Php!

Published Feb 03, 2018Last updated Feb 23, 2018
What is the Factory Method Pattern? Let's implement it in Php!

The Factory Method pattern is part of creational category of design patterns. It is involved in creating something. This something is a product that is loose coupled with the class that creates it (we can call it client).

class diagram factory.png

The Client holds a reference to the Creator (factory interface) for requesting a graphic or text product. The client does not instantiate the product it requests, instead the concrete factories instantiate it. For example, imagine you want to order a pizza with tomato and pepperoni (yes I am Italian). You (client) call the baker (creator) who then makes the cupcakes (product) for you. You are not involved at all with the creation of the object but you still get the pizza requested.

When to use the Factory Method?
Factory Method should be used when the subclass of an object instantiated can vary. In the examples above, all of the subclasses of the Product interface vary; they are different products. The products developed are objects made up of text  and graphics . At the outset, we assume that the developer does not know how many products there will be. In other words, the number and types of objects are unknown. A class cannot anticipate the number of objects it must create, and so you do not want the class tightly bound to the classes it may have to create.

If a class has a finite and known number of objects it must create, the class can be built so that the finite number of objects can be created in a predictable manner. For example, if you are making a world map application with separate objects for the seven continents, you can be fairly certain that they are not going to vary. On the other hand, if you are creating a site for different species of insects, you can be  certain that new ones will be discovered, change, and become extinct over a relatively short period of time. A programming product to deal with that kind of variation needs to have a good deal of flexibility built into it. This is the kind of project where you would want to consider using a Factory Method design.

So, let's see how to implement it with Php
We can start with the abstract class Creator:

//Creator.php
abstract class Creator
{
protected abstract function factoryMethod();
public function startFactory()
{
$mfg= $this->factoryMethod();
return $mfg;
}
}

let's continue with the TextFactory and GraphicFactory that are the concrete implementations of the Creator abstract class:

<?php
    //TextFactory.php
    include_once('Creator.php');
    include_once('TextProduct.php');
    class TextFactory extends Creator
    {
        protected function factoryMethod()
        {
            $product=new TextProduct();
            return($product->getProperties());
        }
} ?>

    <?php
    //GraphicFactory.php
    include_once('Creator.php');
    include_once('GraphicProduct.php');
    class GraphicFactory extends Creator
    {
        protected function factoryMethod()
        {
            $product=new GraphicProduct();
            return($product->getProperties());
        }
} ?>

Both factory implementations are similar other than the fact that one creates a Text Product and the other a GraphicProduct instance.

Time now to see the product interface:

<?php
    //Product.php
    interface Product
    {
        public function getProperties();
    }
?>

You can see where polymorphism comes in with this implementation of the Factory Method in the getProperties() method. It is going to be used to return either “text” or “graphics".

Let's see now the product interface implementations:

<?php
    //TextProduct.php
    include_once('Product.php');
    class TextProduct implements Product
    {
        private $mfgProduct;
        public function getProperties()
        {
            $this->mfgProduct="This is text.";
            return $this->mfgProduct;
        }
} ?>

<?php
    //GraphicProduct.php
    include_once('Product.php');
class GraphicProduct implements Product
    {
        private $mfgProduct;
        public function getProperties()
        {
            $this->mfgProduct="This is a graphic.<3";
            return $this->mfgProduct;
        }
} ?>

You may be thinking, “Big deal, all this does is return a string variable.” At this point, that is true. However, you can put anything you want in the implementation, and the Factory Method design will create and return it to the Client for use. So, where you see the output “This is text,” or “This is a graphic,” imagine any object you may possibly want to create and use.

Let's see now the final participant in this pattern, the client.

You can see now, how the client does not  make a direct request to the product, instead the request goes through the Creator.  If we add later products, the client can make the same request to a much richer variety fo products without breaking the applications:

<?php
    //Client.php
    include_once('GraphicFactory.php');
    include_once('TextFactory.php');
    class Client
    {
        private $someGraphicObject;
        private $someTextObject;
        public function __construct()
        {
            $this->someGraphicObject=new GraphicFactory();
            echo $this->someGraphicObject->startFactory() . "<br />";
            $this->someTextObject=new TextFactory();
            echo $this->someTextObject->startFactory() . "<br />";
} }

    $worker=new Client();
    ?>

Hope you enjoyed this explanation about design pattern Factory Method, and keep in touch for any question or doubt!

Discover and read more posts from Stefano Maglione
get started