Facade pattern in PHP

The facade pattern is today’s structural design pattern. My previous two blogs were about the adapter and the decorator patterns and just like these pattern, the facade pattern is also a known as a wrapper.

The facade pattern does have some similarities to the adapter pattern, in that they’re both used to modify the interface of an entity. However the decorator pattern is used in a very different manner. In case you forgot, here is a quick run down.

Pattern Purpose
Adapter Used to allow incompatible interfaces to work together.
Decorator Allows behaviours to be added to an object, without modifying the original class.
Facade Provides a simplified interface to a more complex library.

What is the facade pattern

The purpose of a facade in development and the real world, is to mask something ugly with something attractive. Taking this information, the facade pattern, is a means of converting the ugly interface of one or more classes into a pretty interface, that you will love to work with (hopefully). This is frequently described as creating a unified interface to a sub system or multiple sub systems.

When to use the facade pattern

The facades patterns ideal use case is when you have legacy code to work with, or when you are working with a 3rd party code. As is usually the case, the code is usually impossible to re-factor as there are no tests. Instead you should create a facade (wrapper) around the original classes to simplify their usage.

When to use a facade and when to use a builder

Facades and builders can sound very similar, they are both used to simplify the usage of a class. However that is where their similarities end.

  1. Builder – These are specific to when initialising a class is long winded. Builders are used to initialise and prepare the objects.
  2. Facade – These can be used to achieve what a builder does, however they are much more aimed at simplifying an interface. This primarily means, renaming methods, merging methods and providing default parameters to methods.

How to use the facade pattern

  1. Create a wrapper class, this is the facade.
  2. Pass the original ugly class instances to the facade.
  3. Use the facade to abstract away the entire sub system and produce a new beautiful API.

Rules

  1. The sub system (this is the ugly object) should not be stored as a static attribute inside the facade. This would result in antichrist global state issues. This is due to how PHP shares static attributes between objects.

Advantages

  1. Allows decoupling your client/controller from your sub system. Meaning less dependencies on you client/controller, meaning changes can be made to your sub system without breaking your client/controller.
  2. Can provide some heavy lifting, by combining multiple method calls into a single call. Similar to that of the adapter and builder patterns.
  3. This is an useful pattern for keeping your code compliant with the law of demeter aka principle of least knowledge. This is done by abstracting away the complicated code into the facade, meaning your client doesn’t have to know about the internals of anything except the facade itself.

Drawbacks

  1. Although extremely useful the facade is often used when there is no need for it, this complicates your code needlessly.This isn’t a drawback as such, just be careful not to fall into this trap.

Example

/**
 * Ok so this looks pretty terrible, right? Everything is public and crappy method names!
 */
interface SendMailInterface
{
    public function setSendToEmailAddress($emailAddress);
    public function setSubjectName($subject);
    public function setTheEmailContents($body);
    public function setTheHeaders($headers);
    public function getTheHeaders();
    public function getTheHeadersText();
    public function sendTheEmailNow();
}

/**
 * Implementing that crappy interface
 */
class SendMail implements SendMailInterface
{
    public $to, $subject, $body;
    public $headers = array();

    public function setSendToEmailAddress($emailAddress)
    {
        $this->to = $emailAddress;
    }
    
    public function setSubjectName($subject)
    {
        $this->subject = $subject;
    }

    public function setTheEmailContents($body)
    {
        $this->body = $body;
    }

    public function setTheHeaders($headers)
    {
        $this->headers = $headers;
    }

    public function getTheHeaders()
    {
        return $this->headers;
    }

    public function getTheHeadersText()
    {
        $headers = "";
        foreach ($this->getTheHeaders() as $header) {
            $headers .= $header . "\r\n";
        }
    }

    public function sendTheEmailNow()
    {
        mail($this->to, $this->subject, $this->body, $this->getTheHeadersText());
    }
}

/**
 * A facade wrapper around the crappy SendMail, to improve method names.
 */
class SendMailFacade
{
    private $sendMail;

    public function __construct(SendMailInterface $sendMail)
    {
        $this->sendMail = $sendMail;
    }

    public function setTo($to)
    {
        $this->sendMail->setSendToEmailAddress($to);
        return $this;
    }
    
    public function setSubject($subject)
    {
        $this->sendMail->setSubjectName($subject);
        return $this;
    }

    public function setBody($body)
    {
        $this->sendMail->setTheEmailContents($body);
        return $this;
    }

    public function setHeaders($headers)
    {
        $this->sendMail->setTheHeaders($headers);
        return $this;
    }

    public function send()
    {
        $this->sendMail->sendTheEmailNow();
    }
}

$to      = "bob@marley.com";
$subject = "Bob Marley and the Wailers";
$body    = "Bob Marley and the Wailers were a Jamaican reggae band created by Bob Marley, Peter Tosh and Bunny Wailer.";
$headers = array(
    "From: Steve@Irwin.com"
);

// Using the minging SendMail class
$sendMail = new SendMail();
$sendMail->setSendToEmailAddress($to);
$sendMail->setSubjectName($subject);
$sendMail->setTheEmailContents($body);
$sendMail->setTheHeaders($headers);
$sendMail->sendTheEmailNow();

// Using the sexy SendMailFacade class
$sendMail       = new SendMail();
$sendMailFacade = new sendMailFacade($sendMail);
$sendMailFacade->setTo($to)->setSubject($subject)->setBody($body)->setHeaders($headers)->send();
35 Love This

14 Comments Facade pattern in PHP

  1. Kabir

    Why we used $sendMail to sendMailFacade parameter ?
    like as
    $sendMailFacade = new sendMailFacade($sendMail);

    The parameter might be sendMailInterface, but there you used sendMail, But none of member of sendMail is used to sendMailFacade. I am confused a little bit.

    Could you explain this.

    Reply
  2. Kabir

    Every thing is ok Sir. I reviewed your code again and again after then I am clear. Have you any video about design pattern.

    Reply
    1. Simon

      Glad you worked it out, I guess you just glazed over line 121? I haven’t made any video content yet. I would recommend checking out the video content on Laracasts. They only cover about 5 videos on design patterns, but the guys content is usually top notch.

      Reply
  3. Danijela

    I’m reading about patterns, and your examples are the best. Very simple, understandable, and I like your writing style. Keep writing πŸ˜€

    Reply
      1. Simon

        Gotta love those Avatars πŸ˜‰ Thanks, I’m glad you find the blog useful. I’ll get my writing hat back on soon. Finishing this design pattern series has been a long time coming.

        Reply
  4. mohammad

    Hello
    SendMailFacade is a wrapper for the ugly sendMail class, yes it’s, and it should be, because the pattern say so, but I knew facade most of the time as static class .
    what you have done up there sir, is just a wrapper which takes the sendMail class in constructor which i know this type of taking as Constructor injection which implement sendMailInterface. and after that we return the same object on each method calling which I know it as Chain ability.
    If you look at facade design patter in laravel, they have been implement this design pattern in a little wired and beutiful way. If i did not read the laravel documentation about facade i did not have any info of what Request facade will do for me .
    what i mean, the class SendMailFacade should be much more cleaner because you said the facade is there to hide the most of the logic. I don’t mean any thing with your example, please don’t miss understand me. i’m just saying a little bit of extracting or cleaning it makes the SendMailFacade looks better . I don’t know maybe I’m just saying that .

    Reply
    1. Simon

      Hi Mohammad,

      Firstly, thanks for the feedback, it’s much appreciated, you have got a valid point. When I write blogs I try to follow the KISS principle, much like when writing code. The problem as you have rightfully pointed out, is that the facade pattern is used to simplify complicated code and my example doesn’t demonstrate this fantastically. You said this

      “SendMailFacade should be much cleaner”

      and the drawback I gave to this pattern was as follows

      “Although extremely useful the facade is often used when there is no need for it, this complicates your code needlessly.This isn’t a drawback as such, just be careful not to fall into this trap.”

      I think this is more the case. It’s not that SendMailFacade is complicated, it’s that SendMail isn’t complicated enough to warrant a facade. The only parts that are being simplified are the send method and the ability to use method chaining.

      In respect to laravel, which is my goto PHP framework right now and I know exactly what your saying. They use a lot of static facades but it’s not standard and it brings about the case of hidden globals and they’re not very testable, which both me less stable code. Laravel has a huge team and have got around the testing problem using Reflection, but it’s not something I wouldn’t encourage others to follow suit.

      Reply

Leave a Reply to Simon Cancel reply

Your email address will not be published.