Manage Complexity with the Facade Pattern

Design patterns are built to standardize solutions for common problems faced in software development. When we develop complex applications, we should allocate sufficient time for planning the design and structure of the app. When we do so, we have the chance to choose appropriate design patterns. But there can be situations where we use a design pattern without even knowing that we’re using one.

Facade is a design pattern used in almost every web application, but often without knowing. The term “design pattern” creates a mental image of something complex and difficult to understand. Even though this can be true sometimes, the Facade pattern is simple to implementation. Let’s see what Facade is and what it does to help us write good code.

The Process of Borrowing a Book

Assume that we’re developing an application for a library management system. Borrowing and returning books are obviously the two most important tasks of such systems. But consider a typical implementation of the book borrowing process:

  • A user comes to the library and returns her borrowed books so she can borrow new ones.
  • The user must pay a fine for overdue books.
  • The user, or a member of the library staff, searches for a new book.
  • The availability of the book is verified.
  • If the steps above are successfully completed, the location of the book must be retrieved.
  • The user borrows the book.
  • The status of the book is marked as unavailable in the system.

The implementation of each task is contained in separate classes with their own interfaces. The following code illustrates how a system might let the user borrow a book by calling the necessary methods:

<?php
public class User
{
    public function borrowBook() {
        $bookManager = new Book_Manager();
        $bookManager->returnBooks();

        $bookPayments = new Book_Payments();
        if ($bookPayments->hasOverdueBooks()) {
            $bookPayments->payBookFines();
        }

        $bookLibrary = new Book_Library();
        $bookReservations = new Book_Reservations();

        $book = $bookLibrary->searchBooks();
        $isAvailable = $bookLibrary->isBookAvailable($book);
        $isReserved = $bookReservations->isBookReserved($book); 
        if ($isAvailable && !isReserved) {
            $bookLibrary->locateBook($book);

            $bookManager->borrowBook($book);
            $bookLibrary->updateBookAvailability($book, $status);
        }
    }
}

You can see the process of borrowing a book is actually a complex process! In this implementation, a user has to interact with four different classes and around ten methods to borrow a book.

Assume that each bit of functionality is implemented as a separate screen in the application; can you imagine the effort required for borrowing three books with this system? And the borrower doesn’t need to know about functionality such as checking reservations and updating the status. We certainly have a problem with our implementation.

Implementing a Library Facade

We need to decouple the user from the complex workflow of the library and allow for a simplified interface exposing just the information directly related to a user – a facade. Let’s see the implementation of the library facade.

<?php
class Library_Facade
{
    public function returnBooks() {
        // previous implementation by calling necessary classes
    }

    public function borrowBooks() {
    }

    public function searchBooks() {
    }

    public function reserveBooks() {
    }
}

The user can borrow books by calling the borrowBook() method of the Library_Facade class as shown in the following example:

<?php
class User
{
    public function borrowBook() {
        $libraryFacade = new Library_Facade();
        $libraryFacade->borrowBook();
    }
}

With this facade-based implementation, the user only talks to the Library_Facade class and has no idea how the functionality is implemented beyond it. A user can directly request any feature from the facade and the facade is responsible for handling the complex process and returning the appropriate information. The Facade pattern adheres to the principle of least knowledge in which each unit should have minimal knowledge about the other units.

Even though the low-level functionality is hidden from the user through the facade, the user can still request low-level classes directly when needed. Think about your own projects and where you might find situations where you’ve implemented the Facade pattern without even realizing it.

Facade Pattern Definition

Since we’ve identified the process and importance of implementing the Facade pattern, now it’s time to learn the definition of the pattern. The following is extracted from Wikipedia:

A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:

  • make a software library easier to use, understand, and test since the facade has convenient methods for common tasks;
  • make the library more readable, for the same reason;
  • reduce dependencies of outside code on the inner workings of a library, since most code uses the facade allowing more flexibility in developing a system;
  • wrap a poorly designed collection of APIs with a single well-designed API.

Here’s a class diagram of our library example that identifies the components mentioned in the Facade pattern definition.

facade-01

Real World Implementations

In the previous sections we learned the theory behind the Facade pattern using a library system as an example. In the real world, facades can be much more complex than the implementation in our library scenario. Let’s review some implementations of the pattern in the context of real-world applications and libraries.

Opauth for Open Authentication

I recently wrote an article about a popular Open Authentication library called Opauth, and I suggest you read it if you haven’t already. Assume we’ve developed a professional social network site and we want our users to be able to use other popular sites such as Twitter, LinkedIn, and Facebook to authenticate. To complete the authentication process we use existing third-party libraries for accessing the networks’ services. Let’s look at some sample code for with a Twitter library for achieving the desired functionality.

<?php
$toauth = new TwitterOAuth('consumer key', 'consumer secret');

$request_token = $toauth->getRequestToken('http://exmaple.com/twitter_oauth.php');

$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

if ($toauth->http_code == 200) {
    $url = $toauth->getAuthorizeURL($request_token['oauth_token']);
    header('Location: '. $url);
}
else {
    // Generate error
}

As you can see, we call a set of Twitter-specific library methods to implement the desired functionality. A similar approach would be necessary for both LinkedIn and Facebook. The process has already become complex. We’re not developing a Twitter, Facebook, or Linkedin application; we should just validate the credentials and authenticate the user. Our application shouldn’t be worried about the implementation of each of these services.

We can solve this problem by using the Opauth library as a facade interface. First we need to specify the login URLs of the desired services in a common format to be identified by the Opauth plugin. Consider the following code for implementing the authentication process.

<?php
public function login($stratergy = '') {
    if ($stratergy != '') {
        $this->opauth_lib->initialize();
    }
}

Once the login link is requested, Opauth identifies the requested service from the URL and initializes the library to redirect the user for authentication. Our application now only needs to create the login links and call the initialize method. All of the complex authentication stuff is handled behind-the-scenes using the respective libraries for each service. This can be considered a perfect example for effectively using the Facade pattern.

WordPress Meta Functions

WordPress is not one of the most popular frameworks among serious PHP developers considering the quality of its code. But we can easily find a number of successful facade implementations inside the WordPress codebase. Here I’ll take a look at the update_post_meta() function for saving custom data for WordPress posts.

WordPress allows us to create custom fields associated with existing posts. Think of how we save these fields in a usual situation… we have to implement all the following tasks:

  • Validate the field data
  • Filter the data for HTML tags, scripts, and SQL injections
  • Check the existence of the field in database
  • Save or update the record based on the existence status

That’s quite a lot of work to save one single custom field! WordPress hides the complexity of saving these fields by providing a built-in function called update_post_meta() to act as a facade. This permits us to focus on passing the necessary data related to our application; all of the aforementioned tasks are hidden from the user.

Now consider the implementation of update_post_meta() to identify its functionality as a facade:

<?php
function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
    // make sure meta is added to the post, not a revision
    if ($the_post = wp_is_post_revision($post_id))
        $post_id = $the_post;

    return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
}

function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
    // expected_slashed ($meta_key)
    $meta_key = stripslashes($meta_key);
    $passed_value = $meta_value;
    $meta_value = stripslashes_deep($meta_value);
    $meta_value = sanitize_meta($meta_key, $meta_value, $meta_type);

    $check = apply_filters("update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value);
    if (null !== $check)
        return (bool) $check;

    // Compare existing value to new value if no prev value given and the key exists only once.
    if (empty($prev_value)) {
        $old_value = get_metadata($meta_type, $object_id, $meta_key);
        if (count($old_value) == 1) {
            if ($old_value[0] === $meta_value)
                return false;
        }
    }

    $wpdb->update($table, $data, $where);
}

Only the necessary code is shown; the complete source code for the update_metadata() function is available in meta.php file inside the wp-includes directory. But you can see all of the validation, filtering, and database updates are implemented here and only the facade interface has knowledge about the details.

Conclusion

Facade is one of the most simple and easy to use design patterns in software development. Throughout this article I talked about various implementations of the Facade pattern. Now it’s time to share your experiences in the comments below. Do you know of any library or service that makes use of facades? Feel free to share the practical implementations of the Facade pattern you’ve come across.

Image via Fotolia

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.mhlavac.net Martin Hlaváč

    Thanks for interesting articles about facades. I think that frameworks are a nice example of their own. For example Symfony 2 with it’s built in services which do work with lot of other services. This means that these services works like facades.

    I personally use facades as managers for solving more complex operations where more services and repositories are used.

    As you have already stated, i find facades as a great way how to allow developer to do what he needs fast. If developer feels restricted he can use all calls that facades uses.

    • http://www.innovativephp.com Rakhitha Nimesh

      Hi Martin

      Thank you for your interest in my article.

      Indeed frameworks hides complexity in most occasions and hence we can see them as facades.
      Thanks for providing other practical usages such as Symphony services. I haven’t used Symphony. so I am definitely going to check that out.

      Do you have any other facade implementations beyond frameworks or libraries.?

  • Fernando Lee

    Great content I would like to see more posts about patterns, and I agree on the fact that many times we use facade without knowing it, it’s nice to call it from the propper name :)

    • http://www.innovativephp.com Rakhitha Nimesh

      Hi Fernando

      Thank you for the suggestions. I’ll try to publish more patterns related topics as they are very important in application development.

      Do you have any practical examples for the usage of facades?

      • miszmaniac

        Hi,
        In our company we use facades for connections with other facilities like java beans. There is much to know about how to connect to java, how to get data from it, but facades hide all that an make public only usable method. example: class AuthorizationFacade … { public function checkCredentials($login,$password); }

        I personally sometimes use facades for dealing with old code. For example, some core code which was written long ago, and didn’t use access modifiers or someone created god class with 50 public methods, which I don’t really care about.

        • http://www.innovativephp.com Rakhitha Nimesh

          Hi miszmaniac
          Thank you very much for sharing your experiences with us.

          Can you explain how you used Facade for dealing with old codes?

          That sounds interesting and looking forward to hear from you.

  • violacase

    The formal facade concept is nicely explained here: http://en.wikipedia.org/wiki/Facade_pattern
    Smart WordPress developers are using it more and more. See e.g.: http://www.toppa.com/toppa-plugin-libraries-for-wordpress/

    • http://www.innovativephp.com Rakhitha Nimesh

      Hi violacase

      Thank you very much for the comment and providing examples for real world Facade implementation.

  • Iain Potter

    Nice article.

    One suggestion – why not use an interface for the facade? That way, any classes that depend on it can be injected with an alternative implementation e.g. for unit testing.

    • http://www.innovativephp.com Rakhitha Nimesh

      Hi Iain
      Thank you very much for your interest in my article.

      Yep. It seems a good idea. Why don’t you share the implementation with interface so that our readers can get more knowledge in Facades.

      Looking forward to your reply.

  • Flávio

    Laraval 4 uses Facades all over the place. Take a look at this short video:
    https://tutsplus.com/lesson/when-they-say-laravel-shouldnt-use-static-methods/
    Thanks for the article!

    • http://www.innovativephp.com Rakhitha Nimesh

      Hi Flavio

      Thanks for liking my article and sharing a valuable video.

      I have heard about the Laravel framework and it’s usage of design patterns. But haven’t had a chance to work with the framework. I’ll be looking at the Laravel implementations of Facade.

    • sebastiaan hilbers

      Ahhhh my eyes… look at facade::__callStatic and how they are “composing” the callback… yuk! for each added argument they have a case in the switch!!! aahhh. Also, the “facade” laravel is using, is just the singleton pattern with an abstracted “facade” class..

      @see https://github.com/laravel/framework/blob/master/src/Illuminate/Support/Facades/Facade.php#L198

  • http://tournasdimitrios1.wordpress.com Tournas Dimitrios

    Allow me to complement your article with a little “Laravel stuff” , just to prove that your article’s subject is a “must understanding” . No matter the implementation , the basic concepts remain the same .
    A Laravel application is represented by an “$app object” (which extends an IoC container) . Instead of “hard coding” dependencies into a Class , these are injected at run-time (into the constructor) . To go one step further , the IoC container is powerful enough to resolve Classes without any prior configuration (it will use PHP’s Reflection facilities to inspect the Classes and read their constructor’s type-hints) . Using this information , the container can automatically build an instance of a Class . A common scenario in Laravel’s Controllers is to inject “concrete type” into their constructors (to achieve automatic instantiation) . Other-times , into Laravel’s Controller constructors are injected “Interface type” , now the IoC will resolve this Interface type to a predefined “concrete Class” . The final result is greater flexibility as dependency implementations may be swapped easily (for instance , mocking a Database object during Unit Testing) .
    In Laravel , Facades provide a “static” interface to objects available into the application’s IoC container . Although Laravel has many predefined Facades (which are registered by using Service providers) , we could also register our own Facades (for instance , bootstrapping a custom Authentication driver) . Lastly , we may also register a Service provider at run-time using the App::register method .
    Thanks for the article , I’ll be glad to read your next “design pattern stuff” .

    • http://www.innovativephp.com Rakhitha Nimesh

      Hi Tournas

      Thanks for the compliments.

      I really like the way you explained the Facades and design patterns inside Laravel framework. You should be a good writer. Am I correct? If so can we see some of the articles you created?

      After hearing your explanations, I feel that I should dig deeper into this awesome new framework.