in oop php object oriented programming design pattern programming refactor solid ~ read.

Factory Pattern

In this post, we are going to talk about how to use Factory Design Pattern in PHP.

What is Factory Pattern and Why?

Using Factory design pattern can hide the instantiation logic and defer it to subclasses. Although it might look a bit too much to write at the beginning but at the long run it will certainly offers you a lot of flexibility.

Demo

Let's say we need to create a website class and based on the type of website it will have different pages. Let's dive into the code now.

First let's create a website class.

<?php

abstract class Website {  
  protected $pages = [];

  public function __construct()
  {
    $this->createWebsites();
  }

  public function getPages()
  {
    return $this->pages;
  }

  abstract public function createWebsites();
}

(Website)

This Website class is going to create our website but it doesn't know the details of the implementation since it defers it to its subclasses. Next let's create two type of websites(subclass).

<?php

class Blog extends Website {  
  public function createWebsites()
  {
    $this->pages[] = "Post Page";
    $this->pages[] = "About Page";
    $this->pages[] = "Contact Page";
  }
}

(Blog)

<?php

class Shop extends Website {  
  public function createWebsites()
  {
    $this->pages[] = "Cart Page";
    $this->pages[] = "Item Page";
    $this->pages[] = "Search Page";
  }
}

(Shop)

All right, next let's create our website factory class that will create our website based on the argument past in.

<?php

class WebsiteFactory {  
  public static function getWebsites($siteType)
  {
    switch ($siteType) {
      case 'blog':
        return new Blog();
        break;

      case 'shop':
        return new Shop();
        break;

      default:
        return null;
        break;
    }
  }
}

(WebsiteFactory)

At the end let's put all of the pieces together and use this pattern.

<?php

use WebsiteFactory;

$site = WebsiteFactory->getWebsite('blog');

echo $site->getPages();

$site = WebsiteFactory->getWebsite('shop');

echo $site->getPages();  

End

Factory Pattern has been used intensely in all kinds of libraries and frameworks and provide more flexibility with the creation of classes. Hope you guys can learn something from this post and play around with it. As always if you have any comments or ideas please leave it below. Thanks!

comments powered by Disqus