[Design Patterns]: The Facade Pattern

This pattern belongs to the structural patterns. It specifies how the code should be structured to be organized and maintainable.

Repetitive code throughout the system can be contained in facade and called with proper arguments to perform specific action.

Example:

class FriendshipFacade
{
   private $notificationService;
   private $userService;
   private $friendshipService;

   public function __construct(
      NotificationService $notificationService,
      UserService $userService,
      FriendshipService $friendshipService
   )
   {
      $this->notificationService = $notificationService;
      $this->userService = $userService;
      $this->friendshipService = $friendshipService;
   }

   public function add($userId1, $userId2)
   {
      $user1 = $this->userService->get($userId1);
      $user2 = $this->userService->get($userId2);

      $this->friendshipService->add($user1, $user2);

      $this->notificationService->notify($user1, 'You have a new friend: ' . $user2->name);
      $this->notificationService->notify($user2, 'You have a new friend: ' . $user1->name);
   }
}


class UserController
{
   public function addFriend()
   {
      $friendshipFacade = new FriendshipFacade();
      $friendshipFacade->add($userId1, $userId2);
   }
}

Majd Arbash

Leave a Reply