In PHP, abstraction refers to the practice of hiding implementation details of a class or an object and only exposing the necessary functionality to the user. It allows developers to create more flexible and maintainable code by reducing the coupling between different parts of the codebase.

Abstraction in PHP can be achieved through several mechanisms, such as interfaces, abstract classes, and traits. These mechanisms allow developers to define a set of methods that must be implemented by any class that implements an interface or extends an abstract class, while still allowing for customization and implementation-specific details.

Using abstraction can also make it easier to modify and extend code in the future, as changes can be made to the implementation details without affecting the code that relies on the abstracted interface. It also helps to make code more testable and easier to debug, as it allows for greater isolation and separation of concerns.

Sure! Here’s an example of abstraction in PHP using an abstract class:

<?php

// Define an abstract class with a method that must be implemented by any subclass
abstract class Animal {
    abstract public function makeSound();
}

// Define a subclass that implements the abstract method
class Dog extends Animal {
    public function makeSound() {
        echo "Woof!";
    }
}

// Define another subclass that implements the abstract method
class Cat extends Animal {
    public function makeSound() {
        echo "Meow!";
    }
}

// Create instances of the subclasses and call the makeSound method
$dog = new Dog();
$dog->makeSound(); // Output: Woof!

$cat = new Cat();
$cat->makeSound(); // Output: Meow!

In this example, we define an abstract class Animal with an abstract method makeSound(). This means that any class that extends Animal must implement the makeSound() method in order to be instantiated.

We then define two subclasses, Dog and Cat, that extend the Animal class and implement the makeSound() method with their own unique behavior.

By using abstraction in this way, we can define a common interface for different types of animals, while still allowing for customization and specific implementation details in each subclass. This can make our code more flexible and maintainable, especially as we add more types of animals in the future.

Real life example of Abstraction

1- Television Remote Control

The remote control of a television is a good example of abstraction. The remote control provides a simple interface to the user, allowing them to turn the TV on and off, change channels, adjust the volume, and perform other tasks without needing to know the underlying technology that makes it all work.

class Television {
  // properties and methods related to the television
}

class RemoteControl {
  public function turnOn(Television $tv) {
    // turns the TV on
  }

  public function turnOff(Television $tv) {
    // turns the TV off
  }

  public function changeChannel(Television $tv, $channel) {
    // changes the channel of the TV
  }

  public function adjustVolume(Television $tv, $volume) {
    // adjusts the volume of the TV
  }
}

// usage:
$tv = new Television();
$remote = new RemoteControl();
$remote->turnOn($tv);
$remote->changeChannel($tv, 5);
$remote->adjustVolume($tv, 10);
$remote->turnOff($tv);

2- Car Dashboard

The dashboard of a car is another example of abstraction. It provides a simple interface that displays information about the car’s speed, fuel level, engine temperature, and other important metrics. The driver doesn’t need to know how the car’s engine works or how the data is collected and displayed, they just need to know how to interpret the information.

class Car {
  // properties and methods related to the car
}

class Dashboard {
  public function displaySpeed(Car $car) {
    // displays the speed of the car
  }

  public function displayFuelLevel(Car $car) {
    // displays the fuel level of the car
  }

  public function displayEngineTemperature(Car $car) {
    // displays the engine temperature of the car
  }
}

// usage:
$car = new Car();
$dashboard = new Dashboard();
$dashboard->displaySpeed($car);
$dashboard->displayFuelLevel($car);
$dashboard->displayEngineTemperature($car);

3- ATM Machine

An ATM machine is another example of abstraction. The user interacts with the machine by selecting options from a menu and entering information such as their PIN and the amount of money they wish to withdraw. The ATM machine takes care of the details of communicating with the bank’s servers and dispensing cash, abstracting away the complexity of the underlying system.

class BankServer {
  public function communicateWithdrawalRequest($amount, $pin) {
    // communicates with the bank's servers to process a withdrawal request
  }
}

class ATM {
  private $bankServer;

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

  public function withdraw($amount, $pin) {
    $this->bankServer->communicateWithdrawalRequest($amount, $pin);
    // dispenses the requested amount of cash
  }
}

// usage:
$bankServer = new BankServer();
$atm = new ATM($bankServer);
$atm->withdraw(100, 1234);

4- Coffee Maker

A coffee maker is an example of abstraction in the kitchen. The user simply adds water and coffee grounds to the machine, presses a button, and waits for the coffee to be brewed. The machine takes care of the details of heating the water, pouring it over the grounds, and filtering the resulting coffee, abstracting away the details of the brewing process.

class CoffeeMaker {
  public function brewCoffee() {
    // heats water, pours it over coffee grounds, and filters the resulting coffee
  }
}

// usage:
$coffeeMaker = new CoffeeMaker();
$coffeeMaker->brewCoffee();

5- Smartphones

Smartphones are a great example of abstraction. They provide a simple interface that allows users to perform a wide variety of tasks, such as making calls, sending texts, browsing the internet, and using apps. The underlying technology that makes all of these things possible is abstracted away from the user, allowing them to focus on what they want to do rather than how to do it.

class Smartphone {
  public function makeCall($phoneNumber) {
    // makes a phone call to the specified phone number
  }

  public function sendText($phoneNumber, $message) {
    // sends a text message to the specified phone number with the specified message
  }

  public function browseInternet($url) {
    // loads the specified URL in the web browser
  }

  // other methods related to using a smartphone
}

// usage:
$phone = new Smartphone();
$phone->makeCall('555-1234');
$phone->sendText('555-5678', 'Hello!');
$phone->browseInternet('https://www.google.com');

Case Study: Online Shopping Cart System

Background: A company wants to create an online shopping cart system for their e-commerce website. The system will allow customers to add items to their cart, view their cart, and checkout. The company has hired a team of software developers to build the system.

Requirements:

  • Customers must be able to view a list of products on the website.
  • Customers must be able to add items to their cart.
  • Customers must be able to view their cart.
  • Customers must be able to update the quantity of items in their cart.
  • Customers must be able to remove items from their cart.
  • Customers must be able to checkout and complete their purchase.
  • The system must be secure, with proper authentication and authorization measures in place.
  • The system must be scalable, able to handle a large number of users and transactions.

Solution: The software development team decides to use an object-oriented approach to build the shopping cart system. They break the system down into several classes:

  1. Product class: This class represents a product that can be purchased. It contains properties such as the product name, description, price, and image.
  2. Cart class: This class represents the customer’s shopping cart. It contains methods to add items to the cart, remove items from the cart, update the quantity of items in the cart, and view the cart.
  3. User class: This class represents a customer using the shopping cart system. It contains properties such as the user’s name, email address, and password.
  4. Order class: This class represents a completed order. It contains properties such as the order number, date, and total price.
  5. Payment class: This class represents a payment made by the customer. It contains properties such as the payment amount, date, and payment method.

The development team also decides to use a database to store the product, user, cart, order, and payment information. They use a combination of SQL and PHP to interact with the database and perform CRUD (Create, Read, Update, Delete) operations.

To ensure security, the development team implements proper authentication and authorization measures. Customers must create an account and log in before they can use the shopping cart system. The system also uses encryption to protect sensitive user data.

To ensure scalability, the development team uses a cloud-based hosting provider that can handle a large number of users and transactions. They also implement caching and load balancing to optimize performance.

// Product class
class Product {
  private $name;
  private $description;
  private $price;
  private $image;

  public function __construct($name, $description, $price, $image) {
    $this->name = $name;
    $this->description = $description;
    $this->price = $price;
    $this->image = $image;
  }

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

  public function getDescription() {
    return $this->description;
  }

  public function getPrice() {
    return $this->price;
  }

  public function getImage() {
    return $this->image;
  }
}

// Cart class
class Cart {
  private $items;

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

  public function addItem($product, $quantity) {
    $this->items[] = array(
      'product' => $product,
      'quantity' => $quantity
    );
  }

  public function removeItem($index) {
    unset($this->items[$index]);
    $this->items = array_values($this->items);
  }

  public function updateQuantity($index, $quantity) {
    $this->items[$index]['quantity'] = $quantity;
  }

  public function getItems() {
    return $this->items;
  }

  public function getTotalPrice() {
    $totalPrice = 0;
    foreach ($this->items as $item) {
      $totalPrice += $item['product']->getPrice() * $item['quantity'];
    }
    return $totalPrice;
  }
}

// User class
class User {
  private $name;
  private $email;
  private $password;

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

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

  public function getEmail() {
    return $this->email;
  }

  public function getPassword() {
    return $this->password;
  }
}

// Order class
class Order {
  private $orderNumber;
  private $date;
  private $totalPrice;

  public function __construct($orderNumber, $date, $totalPrice) {
    $this->orderNumber = $orderNumber;
    $this->date = $date;
    $this->totalPrice = $totalPrice;
  }

  public function getOrderNumber() {
    return $this->orderNumber;
  }

  public function getDate() {
    return $this->date;
  }

  public function getTotalPrice() {
    return $this->totalPrice;
  }
}

This code includes basic implementations of the Product, Cart, User, and Order classes, including their constructors and some basic methods to get and set properties. In a real implementation, these classes would likely be much more complex and include additional methods for interacting with the database, processing payments, and handling user authentication and authorization.

Abstraction in the above code is implemented through the use of classes and methods that hide the underlying complexity of the objects and their interactions.

For example, the Product class encapsulates the properties of a product, such as its name, description, price, and image, and provides methods for getting these properties. The Cart class encapsulates the items in a user’s cart and provides methods for adding, removing, and updating the quantity of items in the cart, as well as getting the total price of the cart.

Similarly, the User class encapsulates the properties of a user, such as their name, email, and password, and provides methods for getting these properties. The Order class encapsulates the properties of an order, such as the order number, date, and total price, and provides methods for getting these properties.

By using these classes and methods, the underlying complexity of the objects and their interactions is hidden from the rest of the program. For example, the Cart class does not expose the implementation details of how it stores the items in the cart, and the Product class does not expose the implementation details of how it stores the product properties.

This allows the rest of the program to interact with these objects in a more abstract and simplified way, without needing to know about the underlying implementation details.

Results:
The online shopping cart system is a success. Customers are able to easily browse and purchase products on the website, and the system is able to handle a large number of users and transactions. The system is also secure, with proper authentication and authorization measures in place to protect user data. Overall, the use of object-oriented programming and a database helped to create a robust and scalable solution for the company’s e-commerce website.

In conclusion, abstraction is a powerful programming concept that allows developers to create simplified and intuitive interfaces for complex systems. By encapsulating the details of an object’s implementation behind a well-defined interface, developers can create code that is easier to read, understand, and maintain.

In the above code example, abstraction is implemented through the use of classes and methods that encapsulate the properties and behavior of the different objects in the system. This abstraction hides the complexity of the underlying implementation details, allowing the rest of the program to interact with the objects in a more abstract and simplified way.

Overall, abstraction is a fundamental concept in software engineering and is essential for creating code that is scalable, maintainable, and easy to use. By applying abstraction principles to your code, you can create systems that are more flexible, easier to understand, and less error-prone, leading to faster development times and better user experiences.

Categorized in: