Member-only story
What is the Facade Design Pattern?
Facade helps us get the most out of our third-party components with a minimal interface

In programming, we nearly always have to work with multiple components at once and make them work together. Some of the problems we may encounter have already been worked out well and are noteworthy.
Structural design patterns basically show how object relationships can be organized in given scenarios. They focus on composing new structures in the most flexible and easy-to-work-with way.
The Facade Design Pattern
The facade design pattern focuses on working with complex components or sets of classes.
The idea is to separate them from client code through a minimalist interface that exposes only what we need. This interface should handle communication with these complex structures and make them work as easily as possible.
Let’s have a class that is supposed to help us work with images. Right now, all we want to do is to be able to create a simple thumbnail. We can use Imagick or some other libraries to do that directly. The only problem is that they have a much broader interface than we currently need.
This is a good use case for the Facade because it exposes only the minimal interface we’ll be using.
<?php
namespace App\Structural\Facade;
use Imagick;
use SplFileInfo;
class Image
{
private Imagick $imagick;
public function __construct()
{
$this->imagick = new Imagick();
}
public function thumbnail(string $filePath, int $width, int $height): true
{
$this->imagick->readImage($filePath);
$this->imagick->setbackgroundcolor('rgb(0, 0, 0)');
$this->imagick->thumbnailImage($width, $height, true, true);
$fileInfo = new SplFileInfo($filePath);
$thumbPath = $fileInfo->getBasename('.' . $fileInfo->getExtension()) . '_thumb' . "." . $fileInfo->getExtension();
if (file_put_contents($thumbPath, $this->imagick)) {
return true;
} else {
throw new \RuntimeException("Could not create thumbnail.");
}
}
}
Right now, we do not have to care about the internal API of Imagick.