Design patterns: Facade, What It Is and How to Use It (PHP)

date: · 4 min
author: Mauto
series: Design Patterns/ part 11/24

The classic Gang of Four patterns, one per part, with practical PHP examples.

  1. Design Patterns
  2. Design patterns: Singleton
  3. Design patterns: Factory Method
  4. Design patterns: Abstract Factory
  5. Design patterns: Builder
  6. Design patterns: Prototype
  7. Design patterns: Adapter
  8. Bridge Pattern in PHP: What It Is, When to Use It, with Examples
  9. Design patterns: Composite
  10. Design patterns: Decorator
  11. Design patterns: Facade, What It Is and How to Use It (PHP)
  12. Design patterns: Flyweight
  13. Design patterns: Proxy
  14. Design patterns: Chain of Responsibility Explained (PHP)
  15. Design patterns: Command
  16. Design patterns: Interpreter
  17. Design patterns: Iterator
  18. Design patterns: Mediator
  19. Design patterns: Memento
  20. Design patterns: Observer
  21. Design patterns: State, What It Is and How to Use It (PHP)
  22. Design patterns: Strategy
  23. Design patterns: Template Method
  24. Design patterns: Visitor
the whole guide >

The Facade Pattern provides a simplified interface to a set of interfaces in a complex system, making the system’s functionality easier to use. It’s especially useful when you want to simplify interaction with a complex system or library.

Characteristics of the Facade Pattern

  1. Simplified interface: The Facade Pattern provides a simplified interface to a complex system or a set of classes, making it easier to interact with these components without having to understand their internal details.
  2. Isolation from the underlying system: It lets you isolate the client from the complexity of the underlying system, reducing dependencies and improving maintainability. Clients don’t need to know the specific classes and how they interact.
  3. Easier to use: It makes a complex system simpler and more intuitive to use, reducing the learning curve for developers and improving the user experience.
  4. Support for code reuse: It can bring existing classes and functionality together behind a single interface, making code reuse easier and simplifying the integration of new features.
  5. Easier changes: It lets you make changes to the underlying system without affecting the client. If the system is updated, the client can keep using the facade without changes.

Example in PHP:

Imagine you have a cinema management system that handles various operations such as managing movies, selling tickets and managing users. A Facade can simplify these interactions for the client code.

// Subsystem: Movie Management
class Movie {
    private $title;
    private $duration; // in minutes

    public function __construct($title, $duration) {
        $this->title = $title;
        $this->duration = $duration;
    }

    public function getTitle() {
        return $this->title;
    }

    public function getDuration() {
        return $this->duration;
    }
}

// Subsystem: Ticket Management
class Ticket {
    private $movie;
    private $seatNumber;

    public function __construct(Movie $movie, $seatNumber) {
        $this->movie = $movie;
        $this->seatNumber = $seatNumber;
    }

    public function getDetails() {
        return "Ticket for the movie '{$this->movie->getTitle()}' in seat {$this->seatNumber}.";
    }
}

// Subsystem: User Management
class User {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

// Subsystem: Movie Catalog
class MovieCatalog {
    private $movies = [];

    public function add(Movie $movie) {
        $this->movies[] = $movie;
    }

    public function findByTitle($title) {
        foreach ($this->movies as $movie) {
            if ($movie->getTitle() == $title) {
                return $movie;
            }
        }
        return null;
    }
}

// Subsystem: User Registry
class UserRegistry {
    private $users = [];

    public function register(User $user) {
        $this->users[] = $user;
    }

    public function findByName($name) {
        foreach ($this->users as $user) {
            if ($user->getName() == $name) {
                return $user;
            }
        }
        return null;
    }
}

// Subsystem: Ticket Office
class TicketOffice {
    public function issueTicket(Movie $movie, $seatNumber) {
        return new Ticket($movie, $seatNumber);
    }
}

// Facade: Cinema System
class CinemaFacade {
    private $catalog;
    private $registry;
    private $ticketOffice;

    public function __construct() {
        $this->catalog = new MovieCatalog();
        $this->registry = new UserRegistry();
        $this->ticketOffice = new TicketOffice();
    }

    public function addMovie($title, $duration) {
        $this->catalog->add(new Movie($title, $duration));
    }

    public function addUser($name) {
        $this->registry->register(new User($name));
    }

    public function bookTicket($userName, $movieTitle, $seatNumber) {
        // Coordinates the subsystems: looks up the user and the movie
        $user = $this->registry->findByName($userName);
        $movie = $this->catalog->findByTitle($movieTitle);

        // If both the user and the movie exist, the ticket office issues the ticket
        if ($user && $movie) {
            $ticket = $this->ticketOffice->issueTicket($movie, $seatNumber);
            return $ticket->getDetails();
        } else {
            return "Booking failed: user or movie not found.";
        }
    }
}

// Using the Facade
$cinema = new CinemaFacade();
$cinema->addMovie("Inception", 148);
$cinema->addMovie("The Matrix", 136);
$cinema->addUser("Alice");
$cinema->addUser("Bob");

// Booking a ticket
echo $cinema->bookTicket("Alice", "Inception", "A1") . "\n";  
// Output: Ticket for the movie 'Inception' in seat A1.

echo $cinema->bookTicket("Bob", "The Matrix", "B2") . "\n";  
// Output: Ticket for the movie 'The Matrix' in seat B2.

echo $cinema->bookTicket("Charlie", "Inception", "C3") . "\n";  
// Output: Booking failed: user or movie not found.

Explanation

  • MovieCatalog, UserRegistry and TicketOffice are the subsystems: each one holds its own data and logic (movies, users, ticket issuing).
  • CinemaFacade holds no data of its own: in bookTicket() it just coordinates the subsystems, looking up the user and the movie and asking the ticket office to issue the ticket.
  • The client code only uses the facade and doesn’t need to know the subsystem classes or the order in which to call them.

BACK TO THE GUIDE

Copied