Home  >  Article  >  Backend Development  >  PHP Design Patterns: An Advanced Application Guide

PHP Design Patterns: An Advanced Application Guide

PHPz
PHPzOriginal
2024-06-04 15:38:00229browse

Answer: This article introduces three PHP design patterns: singleton mode, proxy mode and adapter mode. Detailed description: The singleton pattern ensures that only one instance of a class is created, providing a global access point. The proxy pattern provides a layer of proxy interface to another object to enhance access or control. The Adapter pattern allows compatible and incompatible classes to be used together, making them work with existing client code.

PHP Design Patterns: An Advanced Application Guide

PHP Design Patterns: Advanced Application Guide

Singleton Mode

The singleton mode ensures that a class has only one instance and provides global access point.

class Singleton {
  private static $instance;

  private function __construct() {
    // ...
  }

  public static function getInstance(): Singleton {
    if (!isset(self::$instance)) {
      self::$instance = new Singleton();
    }
    return self::$instance;
  }
}

// 使用
$instance = Singleton::getInstance();

Proxy mode

The proxy mode provides a layer of interface proxy for another object. It enhances access or control of the target object.

class DBConnection {
  private $host;
  private $user;
  // ...

  public function connect() {
    // ...
  }
}

class DBConnectionProxy {
  private $connection;

  public function connect() {
    if (!$this->connection) {
      $this->connection = new DBConnection();
      $this->connection->connect();
    }
    return $this->connection;
  }
}

// 使用
$proxy = new DBConnectionProxy();
$connection = $proxy->connect();

Adapter Pattern

The Adapter pattern enables an incompatible class to be used with existing client code.

class OldPaymentSystem {
  public function charge($amount) {
    // ...
  }
}

class NewPaymentSystem {
  public function pay($amount) {
    // ...
  }
}

class PaymentSystemAdapter {
  private $oldSystem;

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

  public function pay($amount) {
    $this->oldSystem->charge($amount);
  }
}

// 使用
$oldSystem = new OldPaymentSystem();
$adapter = new PaymentSystemAdapter($oldSystem);
$adapter->pay(100);

The above is the detailed content of PHP Design Patterns: An Advanced Application Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn