PHP design patterns from beginner to proficient

王林
Release: 2024-05-07 15:45:02
Original
948 people have browsed it

Design patterns are proven solutions in PHP for creating maintainable, scalable, and reusable code. Basic design patterns can be divided into creative, structural and behavioral. Practical cases demonstrate the application of design patterns in the shopping cart system, including using the factory pattern to create discount service objects, using the proxy pattern to add logging functions to the shopping cart, and implementing various discount calculations through the strategy pattern.

PHP 设计模式从入门到精通

PHP Design Patterns: From Beginner to Mastery

Introduction

Design Patterns are proven code solutions for solving common programming problems. In PHP, design patterns help us write maintainable, extensible, and reusable code.

Basic design pattern

Creative pattern: Provides a mechanism for creating objects.

  • Factory pattern: Create objects without directly specifying a specific class.
  • Single case mode: Ensure that the class only creates an instance once.

Structural pattern: Defines the relationship between classes and objects.

  • Adapter mode: Allows incompatible interfaces to work together.
  • Proxy mode: Provides transparent access to objects.
  • Decorator pattern: Dynamicly add new functionality to existing objects.

Behavioral pattern: Defines how objects communicate and collaborate.

  • Observer pattern: Used for publish/subscribe mechanism.
  • Strategy Mode: Allows the algorithm to be changed at runtime.
  • Template method pattern: Define the algorithm framework and allow subclasses to customize steps.

Practical Case: Shopping Cart

Consider a shopping cart system containing the following classes:

  • Cart : Represents the shopping cart, which stores purchased items.
  • Item: Represents a single item in the shopping cart.
  • DiscountService: Provides an interface for calculating discounts.

Use factory mode to create DiscountService object:

interface DiscountServiceFactory {
  public static function create(): DiscountService;
}

class NormalDiscountService implements DiscountService {
  // ...
}

class PremiumDiscountService implements DiscountService {
  // ...
}

class DiscountServiceFactoryImpl implements DiscountServiceFactory {
  public static function create(): DiscountService {
    if (isPremiumCustomer()) {
      return new PremiumDiscountService();
    }
    return new NormalDiscountService();
  }
}
Copy after login

Use proxy mode to add for Cart Log function:

class CartLoggerProxy extends Cart {
  private $logger;

  public function __construct(Cart $cart, Logger $logger) {
    parent::__construct();
    $this->cart = $cart;
    $this->logger = $logger;
  }

  public function addItem(Item $item): void {
    parent::addItem($item);
    $this->logger->log("Added item to cart");
  }

  // 其他方法类似处理
}
Copy after login

Various discount calculations through strategy mode:

interface DiscountStrategy {
  public function calculateDiscount(Cart $cart): float;
}

class NoDiscountStrategy implements DiscountStrategy {
  public function calculateDiscount(Cart $cart): float {
    return 0;
  }
}

class FlatDiscountStrategy implements DiscountStrategy {
  private $discount;

  public function __construct(float $discount) {
    $this->discount = $discount;
  }

  public function calculateDiscount(Cart $cart): float {
    return $cart->getTotal() * $this->discount;
  }
}

// ... 更多策略

$context = new DiscountContext();

if (isPremiumCustomer()) {
  $context->setStrategy(new PremiumDiscountStrategy());
} else {
  $context->setStrategy(new NoDiscountStrategy());
}

$discount = $context->calculateDiscount();
Copy after login

Conclusion

By using With design patterns, we can create elegant, flexible and maintainable PHP code. The basic design patterns introduced in this article can help us solve a wide range of programming challenges and build high-quality software.

The above is the detailed content of PHP design patterns from beginner to proficient. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!