Provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher- level interface that makes the subsystem easier to use.
As a software developer, one main task we all have to do is deployment. Similar to all of us, when Eric was just starting his career as a developer, he was doing all the deployment jobs manually. He was using a pretty standard way to do this: set server to offline mode, transfer source code files, update the database’s schema, and set server back online:
$server->offline();
$fileSystem->transferFiles();
$database->updateSchema();
$server->online();
This seemed like the ideal way to do it; the process was easy and straightforward. However, as more and more procedures were being introduced, human errors started happening. New procedures such as running tests before transferring files became more frequent. There was one time when his colleague saw Eric rushing back into the office after he had logged out of work for the day. They asked, “Hey Eric! What's the rush?" Eric replied without breaking his stride, “I forgot to update the database before setting the server back online!” As we all know, human errors are inevitable, but they can be minimized. We realize we need a better solution.
What if we are able to encapsulate all the procedures into one simple method? That is so we will not have to worry about forgetting any step. To update the procedures, we just need to update on place. In this case, we can use the Facade Pattern.
Let us see how it looks in code:
class DeployFacade
{
private $server = null;
private $fileSystem = null;
private $database = null;
public function __construct(Server $server, FileSystem $fileSystem, Database $database)
{
$this->server = $server;
$this->fileSystem = $fileSystem;
$this->database = $database;
}
public function deploy()
{
$this->server->offline();
$this->transferFiles();
$this->updateSchema();
$this->online();
}
}
Now every time Eric needs to do a deployment, he just has to do the following:
$deployFacade->deploy();
You may quickly recognize that in reality we are already using something similar to DeployFacade, that is the deployment script. It is an example of the Facade Pattern. In our example, by using Facade Pattern, it provides a unified interface (DeployFacade) to a set of interfaces (Server, FileSystem and Database) in a subsystem. Facade defines a higher level of interface that makes the subsystem easier to use. No more forgetting any step ever again.
Hopefully this simple tutorial helped you with your development. If you like our post, please follow us on Twitter and help spread the word. We need your support to continue. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.