Design pattern in PHP: Facade Pattern

Facade pattern is a pattern that hides details through a simple object that serves as a front-facing access masking more complex underlying or structural code

What problems can it solve?

As we work with subsystems or third-party systems, we may find making calls deep into the logic of the code. If the code is subject to change over time, and our code interacts with it at many different points, we may find ourselves with a serious maintenance problem as the outer-system evolves.

What facade pattern can do?

A Facade is really a very simple concept. It is just a matter of creating a single point of entry for a tier or subsystem.

It helps to decouple distinct subsystem in a project from one another. On the other hand, it is useful and convenient for client coders to have access to simple methods that achieve clear ends. It reduces errors by focusing use of a subsystem in one place.

Implementation

Let’s see an example of facade pattern in PHP. Here I take a computer-related example.

Step 1: create some components class that a computer class needs.

/**
 * cpu
 */
class Cpu
{
	/**
	 * @return void
	 */
	public function run()
	{
		echo "cpu starts to run";
	}
}

/**
 * memory
 */
class Memory
{
	/**
	 * @return void
	 */
	public function run()
	{
		echo "memory starts to run";
	}
}

/**
 * monitor
 */
class Monitor
{
	/**
	 * @return void
	 */
	public function run()
	{
		echo "monitor starts to run";
	}
}

Step 2: create computer class

/**
 * computer
 */
class ComputerFacade
{

	protected $cpu;
	protected $memory;
	protected $monitor;
	
	public function __construct()
	{
		$this->cpu = new Cpu();
		$this->memory = new Memory();
		$this->monitor = new Monitor();
	}


	public function run()
	{
		$this->cpu->run();
		$this->memory->run();
		$this->monitor->run();
	}
}

Step 3: create computer object and execute it

$computer = new ComputerFacade();
$computer->run();

Step 4: run the script and check the result

$ php facade.php
cpu starts running
memory starts running
monitor starts running

Despite the simplicity of the Facade pattern, it is all too easy to forget to use it, especially if you are familiar with the subsystem you are working with.

Pros of visitor pattern

  1. For client codes, it improves the readability and usability of a software library or subsystem by masking interaction with more complex components behind a single (and often simplified) API.
  2. It helps to decouple distinct subsystem in a project from one another.

Cons of visitor pattern

  1. Do not apply with the principle of opening and closing in programming and things will get more complicated when facade class changes.
RSS