PHP - - By Rakhitha Nimesh

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:

public class User
    public function borrowBook() {
        $bookManager = new Book_Manager();

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

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

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

            $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.

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:

class User
    public function borrowBook() {
        $libraryFacade = new Library_Facade();

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.


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.

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

$request_token = $toauth->getRequestToken('');

$_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.

public function login($stratergy = '') {
    if ($stratergy != '') {

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:

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.


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