DIP

 avatar
user_4333156
php
4 months ago
1.4 kB
3
Indexable
<?php

// Abstraction: an interface that both MySQLDatabase and MongoDB will implement
interface DatabaseInterface {
    public function saveOrder($order);
}

// Low-level class: MySQLDatabase now implements the abstraction
class MySQLDatabase implements DatabaseInterface {
    public function saveOrder($order) {
        // Logic to save the order in MySQL database
        echo "Saving order to MySQL database.\n";
    }
}

// Low-level class: MongoDB also implements the same interface
class MongoDB implements DatabaseInterface {
    public function saveOrder($order) {
        // Logic to save the order in MongoDB database
        echo "Saving order to MongoDB.\n";
    }
}

// High-level class: OrderService depends on the abstraction, not a specific implementation
class OrderService {
    private $db;

    // The dependency is injected through the constructor
    public function __construct(DatabaseInterface $db) {
        $this->db = $db;
    }

    public function placeOrder($order) {
        // Some logic for placing the order
        $this->db->saveOrder($order);
    }
}

// Usage: Now we can easily switch between databases by injecting different implementations
$mysqlDatabase = new MySQLDatabase();
$orderService = new OrderService($mysqlDatabase);
$orderService->placeOrder('Order 1');

// Or use MongoDB
$mongoDatabase = new MongoDB();
$orderService = new OrderService($mongoDatabase);
$orderService->placeOrder('Order 2');
Leave a Comment