Info
Open the page on your phone
Tags: #patterns #GoF patterns #structural patterns

Facade

Facade is a structural design pattern that provides a simple and unified interface to a large subsystem of objects. It defines a high-level interface that makes the subsystem more accessible and convenient to use.

The example below demonstrates how to implement a Facade in PHP. Let's imagine that we have a system for sending messages through various channels (email, SMS, etc.).

                        
<?php

// Subsystem for working with email
class EmailSubsystem
{
    public function sendEmail($to, $message)
    {
        echo "Sent an email to address $to: $message\n";
    }
}

// Subsystem for working with SMS
class SMSSubsystem
{
    public function sendSMS($number, $message)
    {
        echo "Sent SMS to number $number: $message\n";
    }
}

// Facade to simplify subsystem usage
class NotificationFacade
{
    private $emailSubsystem;
    private $smsSubsystem;

    public function __construct()
    {
        $this->emailSubsystem = new EmailSubsystem();
        $this->smsSubsystem = new SMSSubsystem();
    }

    // Method for sending notifications via email
    public function sendEmailNotification($to, $message)
    {
        $this->emailSubsystem->sendEmail($to, $message);
    }

    // Method for sending notifications via SMS
    public function sendSMSNotification($number, $message)
    {
        $this->smsSubsystem->sendSMS($number, $message);
    }
}

// Using the facade
$notificationFacade = new NotificationFacade();
$notificationFacade->sendEmailNotification('user@example.com', 'Hello, this is your email notification!');
$notificationFacade->sendSMSNotification('123456789', 'Hello, this is your SMS notification!');

?>
                        
                    

In this example, the `NotificationFacade` serves as a higher-level interface for sending notifications, abstracting the details of working with email and SMS subsystems.